<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Peng Lei on Medium]]></title>
        <description><![CDATA[Stories by Peng Lei on Medium]]></description>
        <link>https://medium.com/@penouc?source=rss-ab3690ce6e5b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xN8Uq3ID1Qn5cFqwPjtgeA.jpeg</url>
            <title>Stories by Peng Lei on Medium</title>
            <link>https://medium.com/@penouc?source=rss-ab3690ce6e5b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:44:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@penouc/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Day 05: Local File Tools]]></title>
            <link>https://medium.com/@penouc/day-05-local-file-tools-18b72777ebf5?source=rss-ab3690ce6e5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/18b72777ebf5</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <dc:creator><![CDATA[Peng Lei]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 03:18:47 GMT</pubDate>
            <atom:updated>2026-07-16T03:18:47.549Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>On Day 04, we implemented the Tool Registry: tools have public schemas, the runtime owns handlers, and the CLI can manually dispatch a tool with --tool.</p><p>But echo is only a mock tool. It proves that the tool path works, but it does not help an agent understand a real codebase.</p><p>Day 05 adds the first useful coding-agent tools: local file observation tools.</p><p>We still do not write files, apply patches, or run arbitrary shell commands. The scope is deliberately narrowed to read-only capabilities:</p><ul><li>list files in the workspace</li><li>read UTF-8 text files inside the workspace</li><li>search text inside workspace files</li></ul><p>These three tools are the foundation for almost every later agent behavior. Before a coding agent changes code, it needs to know what files exist, what a file contains, and where relevant symbols appear.</p><h3>What Are We Solving Today?</h3><p>Today has four deliverables:</p><ol><li>Implement list_files: list files and directories inside the workspace.</li><li>Implement read_file: read UTF-8 text files with a byte limit.</li><li>Implement search_text: search text and return matching lines.</li><li>Register all three tools in the default Tool Registry.</li></ol><p>The demo still uses the manual tool entrypoint introduced on Day 04:</p><pre>npm run dev -- --tool list_files --tool-input &#39;{&quot;path&quot;:&quot;.&quot;,&quot;maxDepth&quot;:1,&quot;limit&quot;:20}&#39;<br>npm run dev -- --tool read_file --tool-input &#39;{&quot;path&quot;:&quot;README.md&quot;,&quot;maxBytes&quot;:1200}&#39;<br>npm run dev -- --tool search_text --tool-input &#39;{&quot;query&quot;:&quot;ToolRegistry&quot;,&quot;path&quot;:&quot;apps/mini-harness/src&quot;,&quot;limit&quot;:10}&#39;</pre><h3>Where Does This Fit in Cursor/Codex?</h3><p>Today implements <strong>local observation tools</strong>.</p><p>Before systems like Cursor, Codex, and Claude Code modify code, they first observe the workspace:</p><pre>What files exist?<br>What does this file contain?<br>Where is this symbol mentioned?<br>Which module owns this behavior?</pre><p>These questions cannot be answered from model training data alone. They must come from the current workspace.</p><p>Day 05 sits here:</p><pre>User<br>  -&gt; CLI surface<br>    -&gt; ToolRegistry<br>      -&gt; list_files<br>      -&gt; read_file<br>      -&gt; search_text<br>    -&gt; workspace path guard<br>    -&gt; Node fs / ripgrep<br>    -&gt; ToolResult</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CuW7Lg53k6r7eTqa9wUQdg.png" /></figure><p>The boundary matters: today is read-only local observation. No writes, no arbitrary shell commands, and no access outside the workspace.</p><h3>Design</h3><h3>1. Every Path Goes Through a Workspace Guard</h3><p>The largest risk in local file tools is not code complexity. It is an unclear boundary.</p><p>If read_file can read any path on the machine, it is no longer a project-observation tool. It becomes a general local file-reading capability. Once an agent loop is added, that would be a dangerous default.</p><p>So every Day 05 file tool first resolves paths like this:</p><pre>const resolvedPath = resolve(workspaceRoot, inputPath);<br>const relativePath = relative(workspaceRoot, resolvedPath);</pre><p>If the path escapes the workspace, the tool fails:</p><pre>[mini-harness] Error: Path is outside workspace: ../package.json</pre><h3>2. list_files Filters Generated Directories by Default</h3><p>list_files skips common large directories:</p><ul><li>.git</li><li>node_modules</li><li>dist</li><li>.next</li><li>coverage</li></ul><p>It also supports two limits:</p><ul><li>maxDepth</li><li>limit</li></ul><p>This is not polish. It protects context. File lists grow quickly, especially in Node projects. Tools that can return large output need truncation from the beginning.</p><h3>3. read_file Supports a Byte Limit</h3><p>read_file returns:</p><pre>{<br>  path,<br>  content,<br>  bytes,<br>  returnedBytes,<br>  truncated<br>}</pre><p>By default it returns at most 40KB. Callers can pass maxBytes, but the value is still clamped to an upper bound.</p><p>This is still a simplified implementation. It assumes the target is a UTF-8 text file. Later we can add binary detection, file-type handling, and line-based reads.</p><h3>4. search_text Prefers rg, Then Falls Back to Node</h3><p>Text search tries rg first:</p><pre>rg --line-number --no-heading --color never --fixed-strings ...</pre><p>The reason is practical: rg is fast enough for codebases and matches developer expectations.</p><p>But the demo should not fail completely if a machine does not have rg. The handler keeps a Node fallback that recursively reads text files and matches lines.</p><p>The returned structure is:</p><pre>{<br>  root,<br>  query,<br>  matches: [<br>    { path, lineNumber, line }<br>  ],<br>  count,<br>  truncated<br>}</pre><h3>5. Day 05 Still Does Not Let the Model Call Tools Automatically</h3><p>Every demo today still uses explicit --tool.</p><p>That is intentional. We are extending runtime capability, not building a model-driven agent loop yet. Day 06 will connect the “observe -&gt; decide -&gt; act -&gt; observe” path.</p><h3>Implementation Steps</h3><h3>1. Add a Local File Tools Module</h3><p>File: apps/mini-harness/src/tools/local-files.ts</p><p>The module entrypoint is:</p><pre>export function registerLocalFileTools(registry: ToolRegistry, workspaceRoot: string): void {<br>  const root = resolve(workspaceRoot);</pre><pre>  for (const tool of createLocalFileTools(root)) {<br>    registry.register(tool);<br>  }<br>}</pre><p>It receives the registry and the workspace root, then registers three tools.</p><h3>2. Implement list_files</h3><p>The list_files schema:</p><pre>{<br>  type: &quot;object&quot;,<br>  properties: {<br>    path: { type: &quot;string&quot; },<br>    maxDepth: { type: &quot;number&quot; },<br>    limit: { type: &quot;number&quot; },<br>  },<br>}</pre><p>Example:</p><pre>npm run dev -- --tool list_files --tool-input &#39;{&quot;path&quot;:&quot;.&quot;,&quot;maxDepth&quot;:1,&quot;limit&quot;:20}&#39;</pre><p>Example output summary:</p><pre>{<br>  &quot;root&quot;: &quot;.&quot;,<br>  &quot;files&quot;: [<br>    { &quot;path&quot;: &quot;apps&quot;, &quot;type&quot;: &quot;directory&quot; },<br>    { &quot;path&quot;: &quot;articles/day-05-local-file-tools.md&quot;, &quot;type&quot;: &quot;file&quot;, &quot;size&quot;: 9426 }<br>  ],<br>  &quot;count&quot;: 20,<br>  &quot;truncated&quot;: true<br>}</pre><h3>3. Implement read_file</h3><p>The read_file schema:</p><pre>{<br>  type: &quot;object&quot;,<br>  properties: {<br>    path: { type: &quot;string&quot; },<br>    maxBytes: { type: &quot;number&quot; },<br>  },<br>  required: [&quot;path&quot;],<br>}</pre><p>Example:</p><pre>npm run dev -- --tool read_file --tool-input &#39;{&quot;path&quot;:&quot;README.md&quot;,&quot;maxBytes&quot;:1200}&#39;</pre><p>The output includes content, total file bytes, returned bytes, and whether the result was truncated.</p><h3>4. Implement search_text</h3><p>The search_text schema:</p><pre>{<br>  type: &quot;object&quot;,<br>  properties: {<br>    query: { type: &quot;string&quot; },<br>    path: { type: &quot;string&quot; },<br>    limit: { type: &quot;number&quot; },<br>    caseSensitive: { type: &quot;boolean&quot; },<br>  },<br>  required: [&quot;query&quot;],<br>}</pre><p>Example:</p><pre>npm run dev -- --tool search_text --tool-input &#39;{&quot;query&quot;:&quot;ToolRegistry&quot;,&quot;path&quot;:&quot;apps/mini-harness/src&quot;,&quot;limit&quot;:10}&#39;</pre><p>It returns matching lines:</p><pre>{<br>  &quot;matches&quot;: [<br>    {<br>      &quot;path&quot;: &quot;apps/mini-harness/src/tools/registry.ts&quot;,<br>      &quot;lineNumber&quot;: 10,<br>      &quot;line&quot;: &quot;export class ToolRegistry {&quot;<br>    }<br>  ]<br>}</pre><h3>5. Register the Tools in the Default Registry</h3><p>File: apps/mini-harness/src/tools/registry.ts</p><p>createDefaultToolRegistry() now receives a workspace root and registers the local file tools:</p><pre>export function createDefaultToolRegistry(workspaceRoot = process.env.INIT_CWD ?? process.cwd()): ToolRegistry {<br>  const registry = new ToolRegistry();</pre><pre>  registry.register(...echo);<br>  registerLocalFileTools(registry, workspaceRoot);</pre><pre>  return registry;<br>}</pre><h3>Demo</h3><p>See: <a href="https://github.com/penouc/cli-harness/blob/main/demos/day-05/README.md">Day 05 demo</a></p><p>List files:</p><pre>npm run dev -- --tool list_files --tool-input &#39;{&quot;path&quot;:&quot;.&quot;,&quot;maxDepth&quot;:1,&quot;limit&quot;:20}&#39;</pre><p>Read a file:</p><pre>npm run dev -- --tool read_file --tool-input &#39;{&quot;path&quot;:&quot;README.md&quot;,&quot;maxBytes&quot;:1200}&#39;</pre><p>Search text:</p><pre>npm run dev -- --tool search_text --tool-input &#39;{&quot;query&quot;:&quot;ToolRegistry&quot;,&quot;path&quot;:&quot;apps/mini-harness/src&quot;,&quot;limit&quot;:10}&#39;</pre><p>Paths outside the workspace are rejected:</p><pre>npm run dev -- --tool read_file --tool-input &#39;{&quot;path&quot;:&quot;../package.json&quot;}&#39;</pre><p>Output:</p><pre>[mini-harness] Error: Path is outside workspace: ../package.json</pre><h3>Current System Capability</h3><p>After Day 05, the mini harness has its first real observation tools:</p><ul><li>list_files can inspect the workspace file structure.</li><li>read_file can read text files.</li><li>search_text can search code and documentation.</li><li>Tool output still flows through ToolResult.</li><li>--context-report and --transcript can record file observation results.</li><li>All local file access is constrained to the workspace.</li></ul><p>Still missing:</p><ul><li>model-driven tool selection</li><li>multi-step observe/action loops</li><li>file writes or patches</li><li>approval and sandboxing</li><li>fuller binary-file and large-file handling</li></ul><h3>Problems Encountered</h3><h3>1. File Tools Need Stronger Boundaries Than a Mock Tool</h3><p>If echo is called incorrectly, it returns the wrong result. If read_file is called incorrectly, it may read a file that should never enter model context.</p><p>So the point of Day 05 is not merely “can read files.” The point is “can only read files inside a clear boundary.”</p><h3>2. Search Needs to Handle Missing rg</h3><p>rg is the preferred path, but it should not be the only path. The Node fallback keeps the demo stable.</p><p>The fallback is not as fast as rg, and it does not implement full ignore-rule behavior. It only preserves the smallest useful capability.</p><h3>3. Truncation Is Not Optional</h3><p>Local file tool output will eventually enter model context. Any tool that returns a large amount of text needs limit, maxBytes, and truncated.</p><p>Otherwise, Day 08’s context builder will be forced to manage tool-output explosions after the fact.</p><h3>Tomorrow</h3><p>Day 06 will implement the Agent Loop.</p><p>At that point, the model will no longer only answer text, and we will no longer need to call tools manually with --tool. It will enter the smallest loop:</p><pre>observe -&gt; decide -&gt; act -&gt; observe -&gt; final</pre><p>Today’s three local file tools will become the first observation tools inside that loop.</p><p>Originally published at penglei.dev</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18b72777ebf5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 04: Tool Registry]]></title>
            <link>https://medium.com/@penouc/day-04-tool-registry-7f835434204c?source=rss-ab3690ce6e5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f835434204c</guid>
            <category><![CDATA[harness-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Peng Lei]]></dc:creator>
            <pubDate>Thu, 16 Jul 2026 03:13:53 GMT</pubDate>
            <atom:updated>2026-07-16T03:13:53.297Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi, this week’s note is a more structured version of a recent post from my personal blog.</p><h3>Introduction</h3><p>On Day 03, we connected the minimal chat loop: the CLI turns the user task into system/user messages, sends them to a model provider, and receives an assistant message.</p><p>But an agent with only a chat loop is still stuck at the “can talk” stage. Coding agents become useful because they can read files, search code, execute commands, generate diffs, request approvals, and write patches. Inside the harness, all of these capabilities first need to be modeled as <strong>tools</strong>.</p><p>Day 04 does not build real file tools yet, and it does not let the model decide which tool to call. Today only lays the first foundation for the tool layer: the Tool Registry.</p><p>The Tool Registry answers a very practical set of questions:</p><ul><li>What tools exist?</li><li>What input does each tool need?</li><li>What schema should the model see?</li><li>When the runtime receives a tool name and arguments, how does it find the handler?</li><li>Where should unknown tool errors, invalid arguments, and handler failures appear?</li></ul><h3>What Are We Solving Today?</h3><p>Today has four deliverables:</p><ol><li>Define the public tool schema: name, description, and inputSchema.</li><li>Define the internal registered tool: public schema + handler.</li><li>Implement register(), list(), and dispatch().</li><li>Add the first mock tool: echo.</li></ol><p>We also add a manual tool-call entrypoint to the CLI:</p><pre>npm run dev -- --tool echo --tool-input &#39;{&quot;text&quot;:&quot;hello&quot;}&#39;</pre><p>This command is not an agent loop. It only proves that the registry can dispatch from a tool name to a handler and return a structured result.</p><h3>Where Does This Fit in Cursor/Codex?</h3><p>Today implements the <strong>tool definition layer</strong> and the smallest <strong>tool runtime</strong>.</p><p>In systems such as Cursor, Codex, and Claude Code, the tool layer usually serves two sides:</p><pre>Model side<br>  -&gt; sees tool name, description, JSON schema</pre><pre>Runtime side<br>  -&gt; owns handler, validation, dispatch, errors, result logging</pre><p>The model should not see the handler. A handler may read files, execute commands, or write patches. Those are real runtime capabilities.</p><p>The runtime also cannot rely only on natural-language tool descriptions. It needs stable schemas and a dispatch table. Otherwise, once dozens of tools are added, every call becomes fragile if/else logic.</p><p>Day 04 sits here:</p><pre>User<br>  -&gt; CLI surface<br>    -&gt; chat loop<br>    -&gt; tool registry<br>      -&gt; tool schema list<br>      -&gt; manual dispatch<br>      -&gt; echo handler<br>    -&gt; context report / transcript</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X8kbHbGTVPT4MTly3ItTag.png" /></figure><p>The diagram shows the Day 04 tool registry flow: the model side only sees ToolDefinition and the schema list; the runtime side stores RegisteredTool, which is the public definition plus the real handler. Manual dispatch looks up the tool by name, validates input, executes the handler, and returns a structured ToolResult.</p><p>Day 06 will connect this line into the agent loop, so the model can decide whether to call a tool. Today we only make the runtime capable of calling one.</p><h3>Design</h3><h3>1. ToolDefinition Is for the Model</h3><p>The shared package already has ToolDefinition:</p><pre>export type ToolDefinition = {<br>  name: string;<br>  description: string;<br>  inputSchema: JsonSchema;<br>};</pre><p>This part enters the context report today, and later it will describe the tools available to the model.</p><p>For echo, the public definition is:</p><pre>{<br>  name: &quot;echo&quot;,<br>  description: &quot;Return the provided input. Used as the first mock tool before real file tools exist.&quot;,<br>  inputSchema: {<br>    type: &quot;object&quot;,<br>    properties: {<br>      text: { type: &quot;string&quot; },<br>    },<br>    required: [&quot;text&quot;],<br>  },<br>}</pre><p>This deliberately uses JSON Schema style instead of TypeScript types. Model APIs, MCP, plugin systems, and many agent runtimes tend to describe tool input with JSON Schema.</p><h3>2. RegisteredTool Is Internal Runtime State</h3><p>The runtime needs one extra thing that the model should not see: the handler.</p><pre>export type ToolHandler = (input: unknown) =&gt; Promise&lt;unknown&gt; | unknown;</pre><pre>export type RegisteredTool = ToolDefinition &amp; {<br>  handler: ToolHandler;<br>};</pre><p>The handler is not exposed to the model. When list() returns tool definitions, it strips the handler:</p><pre>list(): ToolDefinition[] {<br>  return [...this.tools.values()].map(({ handler: _handler, ...definition }) =&gt; definition);<br>}</pre><p>This boundary matters. The model only proposes “which tool to call and with what arguments.” The runtime performs the actual execution.</p><h3>3. dispatch() Returns a Structured Result</h3><p>Day 04’s dispatch() does not return only the handler output. It returns a ToolResult:</p><pre>export type ToolResult = {<br>  name: string;<br>  input: unknown;<br>  output: unknown;<br>  durationMs: number;<br>};</pre><p>This creates room for later transcript logging. A tool call should at least know:</p><ul><li>which tool was called</li><li>what input was passed</li><li>what output came back</li><li>how long it took</li></ul><p>Day 07 will split these results further into JSONL events.</p><h3>4. Start with a Small Schema Validator</h3><p>A full JSON Schema validator can become complex. Day 04 does not add another dependency. It implements a small subset:</p><ul><li>object</li><li>array</li><li>string</li><li>number</li><li>boolean</li><li>null</li><li>required fields</li><li>nested properties</li></ul><p>That is enough for echo, and enough to keep extending into Day 05&#39;s list_files, read_file, and search_text.</p><p>If input does not match the schema, the runtime throws a clear error:</p><pre>[mini-harness] Error: Invalid input for echo: missing required property &quot;text&quot;<br>[mini-harness] Error: Invalid input for echo.text: expected string</pre><h3>Implementation Steps</h3><h3>1. Extend Shared Types</h3><p>File: packages/shared/src/types.ts</p><p>Day 04 extends the JsonSchema type list and adds ToolCall / ToolResult:</p><pre>export type ToolCall = {<br>  name: string;<br>  input: unknown;<br>};</pre><pre>export type ToolResult = {<br>  name: string;<br>  input: unknown;<br>  output: unknown;<br>  durationMs: number;<br>};</pre><p>The shared package now contains:</p><ul><li>model message types: ChatMessage</li><li>tool definition type: ToolDefinition</li><li>tool call/result types: ToolCall, ToolResult</li></ul><h3>2. Implement ToolRegistry</h3><p>File: apps/mini-harness/src/tools/registry.ts</p><p>Core structure:</p><pre>export class ToolRegistry {<br>  private readonly tools = new Map&lt;string, RegisteredTool&gt;();</pre><pre>  register(tool: RegisteredTool): void {<br>    if (this.tools.has(tool.name)) {<br>      throw new Error(`Tool already registered: ${tool.name}`);<br>    }<br>    this.tools.set(tool.name, tool);<br>  }</pre><pre>  list(): ToolDefinition[] {<br>    return [...this.tools.values()].map(({ handler: _handler, ...definition }) =&gt; definition);<br>  }</pre><pre>  async dispatch(name: string, input: unknown): Promise&lt;ToolResult&gt; {<br>    const tool = this.tools.get(name);<br>    if (!tool) {<br>      throw new Error(`Unknown tool: ${name}`);<br>    }<br>    validateInput(tool.inputSchema, input, name);</pre><pre>    const startedAt = performance.now();<br>    const output = await tool.handler(input);</pre><pre>    return {<br>      name,<br>      input,<br>      output,<br>      durationMs: Math.round(performance.now() - startedAt),<br>    };<br>  }<br>}</pre><p>Three decisions here are deliberate:</p><ol><li>Registering the same tool name twice throws.</li><li>list() never exposes handlers.</li><li>dispatch() validates input before executing the handler.</li></ol><h3>3. Register the echo Mock Tool</h3><p>createDefaultToolRegistry() now registers an echo tool:</p><pre>registry.register({<br>  name: &quot;echo&quot;,<br>  description: &quot;Return the provided input. Used as the first mock tool before real file tools exist.&quot;,<br>  inputSchema: {<br>    type: &quot;object&quot;,<br>    properties: {<br>      text: { type: &quot;string&quot; },<br>    },<br>    required: [&quot;text&quot;],<br>  },<br>  handler: (input: unknown) =&gt; input,<br>});</pre><p>This tool has no product value, but it is perfect for validating the tool path. It exposes every critical point:</p><ul><li>whether schema enters the context</li><li>whether JSON input can be parsed</li><li>whether the registry can find the tool</li><li>whether the handler executes</li><li>whether the result enters transcript/context report</li></ul><h3>4. Add a Manual Tool Call Entrypoint to the CLI</h3><p>File: apps/mini-harness/src/cli.ts</p><p>Two arguments were added:</p><pre>--tool echo<br>--tool-input &#39;{&quot;text&quot;:&quot;hello&quot;}&#39;</pre><p>Command:</p><pre>npm run dev -- --tool echo --tool-input &#39;{&quot;text&quot;:&quot;hello&quot;}&#39;</pre><p>Output includes:</p><pre>[mini-harness] Tool result: {&quot;name&quot;:&quot;echo&quot;,&quot;input&quot;:{&quot;text&quot;:&quot;hello&quot;},&quot;output&quot;:{&quot;text&quot;:&quot;hello&quot;},&quot;durationMs&quot;:0}</pre><p>If --context-report is also enabled, the tool result becomes a tool-results context part. Because this is a manual tool-dispatch demo, it does not call the model, so the tool-only run shows provider as none.</p><h3>Demo</h3><p>The full demo record lives in demos/day-04/README.md in the project repository.</p><p>Manual echo call:</p><pre>npm run dev -- --tool echo --tool-input &#39;{&quot;text&quot;:&quot;hello&quot;}&#39;</pre><p>With context report:</p><pre>npm run dev -- --context-report --tool echo --tool-input &#39;{&quot;text&quot;:&quot;hello&quot;}&#39;</pre><p>Invalid input example:</p><pre>npm run dev -- --tool echo --tool-input &#39;{&quot;text&quot;:123}&#39;</pre><p>Expected error:</p><pre>[mini-harness] Error: Invalid input for echo.text: expected string</pre><h3>What Changed in the System?</h3><p>After Day 04, the system has these new capabilities:</p><ul><li>CLI run summary continues to include tool definitions in context.</li><li>The runtime has an extensible ToolRegistry.</li><li>Tool registration and public tool definitions are separated.</li><li>Manual CLI arguments can trigger tool dispatch.</li><li>Tool input goes through minimal schema validation.</li><li>Tool execution returns a structured ToolResult.</li><li>Transcripts can include tool execution results.</li></ul><p>Still missing:</p><ul><li>model-selected tool calls</li><li>multi-step agent loop</li><li>structured event logs for tool failures</li><li>real file tools</li><li>approval/sandbox</li></ul><h3>Problems Encountered</h3><h3>1. Do Not Turn Day 04 into a Fake Agent Loop</h3><p>It would be tempting to write a natural-language match such as “if the user says echo, call echo.” But that would push the harness in the wrong direction.</p><p>The real agent loop should let the model output tool-call intent, and then let the runtime execute that tool. Day 04 is not there yet, so the CLI only exposes an explicit --tool parameter as the demo entrypoint.</p><h3>2. Keep JSON Schema Scope Small</h3><p>Full JSON Schema includes many features: oneOf, enum, additionalProperties, minimum, format, and more. None of that is needed today.</p><p>Implementing a full schema validator too early would shift the article away from agent harness design and into schema details. Today only implements the subset Day 04 needs.</p><h3>3. Tool Results Should Be Structured from the Start</h3><p>If dispatch() returned only the handler output, transcript support would later have to re-wrap the call details. Returning ToolResult now makes later extension more natural.</p><h3>Tomorrow</h3><p>Day 05 will implement local file tools:</p><ul><li>list_files</li><li>read_file</li><li>search_text</li></ul><p>At that point, echo moves back into a test/example role, and the registry starts carrying genuinely useful coding-agent tools.</p><p>Read the original post at penglei.dev</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f835434204c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 03: LLM Chat Loop]]></title>
            <link>https://medium.com/@penouc/day-03-llm-chat-loop-7a7bb9021f71?source=rss-ab3690ce6e5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a7bb9021f71</guid>
            <category><![CDATA[harness-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Peng Lei]]></dc:creator>
            <pubDate>Sun, 12 Jul 2026 13:23:16 GMT</pubDate>
            <atom:updated>2026-07-12T13:23:16.853Z</atom:updated>
            <content:encoded><![CDATA[<p>Day 03 of the Mini Coding Agent Harness series: defining chat messages and model providers, then upgrading the CLI from static scaffold output to a minimal chat loop.</p><h3>Introduction</h3><p>On Day 02, we set up the TypeScript workspace, CLI entrypoint, context report placeholder, and transcript placeholder. That CLI did not call a model yet. It only printed a scaffold summary.</p><p>Day 03 enters the core data flow of a coding agent: take the user task, organize it into chat messages, send those messages to a model provider, then bring the assistant message back into the harness.</p><p>We are not implementing tool calls today. We are also not building a multi-step agent loop yet. The reason is simple: before adding a tool registry, file tools, approval, or patch editing, we need to stabilize the smallest boundary around model calls. Otherwise, every later capability will end up mixed into cli.ts, making the system hard to test and hard to switch across model providers.</p><h3>What Are We Solving Today?</h3><p>Today has four deliverables:</p><ol><li>Define three chat message roles: system, user, and assistant.</li><li>Define a ModelProvider interface so the harness is not tied to one model API.</li><li>Implement a default mock provider so the demo still works without an API key.</li><li>Implement an OpenAI-compatible non-streaming provider, with DeepSeek V4 Pro as the default real-model example.</li></ol><p>Run it with:</p><pre>npm run dev -- &quot;explain what an agent harness is&quot;<br>npm run dev -- --context-report &quot;explain what an agent harness is&quot;<br>npm run dev -- --transcript logs/runs/day-03.jsonl &quot;explain what an agent harness is&quot;</pre><p>If neither OPENCODE_API_KEY nor OPENAI_API_KEY is configured, the CLI uses the local mock provider. If OPENCODE_API_KEY is configured, the CLI calls opencode Go&#39;s OpenAI-compatible /chat/completions API, using deepseek-v4-pro by default.</p><p>The <a href="https://opencode.ai/go?ref=RRWCDRNFVQ">opencode Go plan</a> can call DeepSeek V4 Pro. If you only want to try a coding-agent tool first, opencode is the direct path; if you want to understand how a harness connects to a model, this article breaks down the provider layer.</p><h3>Where Does This Fit in Cursor/Codex?</h3><p>Today implements the <strong>model adapter</strong> and the smallest form of <strong>conversation state</strong>.</p><p>In products such as Cursor, Codex, and Claude Code, model calls usually are not scattered directly across UI or CLI code. A harness layer sits in between and turns inputs into a structure the model can understand:</p><ul><li>system prompt</li><li>user request</li><li>conversation history</li><li>tool definitions</li><li>selected context</li><li>safety/rules guidance</li></ul><p>Day 03 only includes the minimal set:</p><pre>User<br>  -&gt; CLI surface<br>    -&gt; system message<br>    -&gt; user message<br>    -&gt; model provider<br>    -&gt; assistant message<br>    -&gt; context report / transcript</pre><p>Tool definitions still only appear in the context report today. They are not callable by the model yet. The real tool registry starts on Day 04.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6xlElsgvWjBpOxAORs6Ww.png" /></figure><p>The image above shows the minimal Day 03 chat loop: a user task enters the CLI, becomes system/user messages, goes through a model provider, and returns as an assistant message. The provider can be local mock, DeepSeek, or another OpenAI-compatible API. The assistant message then becomes part of the context report and transcript.</p><h3>Design</h3><h3>1. Messages Are the Basic Currency of the Harness</h3><p>The shared package adds a minimal message type:</p><pre>export type ChatRole = &quot;system&quot; | &quot;user&quot; | &quot;assistant&quot;;</pre><pre>export type ChatMessage = {<br>  role: ChatRole;<br>  content: string;<br>};</pre><p>This structure is plain, but it is the entrypoint for later capabilities. Tool results, file summaries, rules, and compressed history will all eventually become some form of model context. Today we only make the message line work.</p><h3>2. The Provider Interface Lives in the App Runtime</h3><p>apps/mini-harness/src/model/provider.ts defines the provider interface:</p><pre>export type ModelProvider = {<br>  name: string;<br>  chat(messages: ChatMessage[]): Promise&lt;ChatMessage&gt;;<br>};</pre><p>The CLI does not care whether the underlying provider is mock, OpenAI, an OpenAI-compatible API, or a future local model. It only knows this: give the provider a list of messages, get one assistant message back.</p><p>This abstraction has two direct benefits:</p><ul><li>The Day 03 demo can run reliably without network access or API keys.</li><li>Switching model providers later does not require changes to the CLI, context report, or transcript data structures.</li></ul><h3>3. Use a Mock Provider by Default</h3><p>Real LLM calls introduce three variables: API key, network access, and provider response format. For a teaching harness, if the first demo command requires an external service, readers can get blocked by environment setup before they understand the architecture.</p><p>So today’s default behavior is:</p><pre>No OPENCODE_API_KEY / OPENAI_API_KEY -&gt; mock provider<br>OPENCODE_API_KEY exists              -&gt; opencode Go / DeepSeek V4 Pro provider<br>OPENAI_API_KEY exists                -&gt; OpenAI-compatible fallback provider</pre><p>The mock provider does not pretend to be intelligent. It returns deterministic text to prove that the chat loop data flow is connected:</p><pre>[mini-harness] Model provider: mock<br>[mini-harness] Mock model response:</pre><h3>4. Configure DeepSeek V4 Pro with .env</h3><p>The main real-model example uses DeepSeek V4 Pro through opencode Go. opencode Go exposes an OpenAI-compatible chat completions endpoint, so the harness still only needs one OpenAI-compatible provider.</p><p>The project root includes .env.example:</p><pre>OPENCODE_API_KEY=<br>OPENCODE_BASE_URL=https://opencode.ai/zen/go/v1<br>MINI_HARNESS_MODEL=deepseek-v4-pro</pre><p>Copy it before running the real-model demo:</p><pre>cp .env.example .env</pre><p>Then fill in OPENCODE_API_KEY. The Day 03 CLI reads environment variables, so load .env into the current shell before running:</p><pre>set -a<br>source .env<br>set +a<br>npm run dev -- &quot;explain what an agent harness is&quot;</pre><p>Only OPENCODE_API_KEY is required. OPENCODE_BASE_URL and MINI_HARNESS_MODEL have defaults. The code appends /chat/completions to the base URL, so the base value should be https://opencode.ai/zen/go/v1; the full request endpoint becomes <a href="https://opencode.ai/zen/go/v1/chat/completions.">https://opencode.ai/zen/go/v1/chat/completions.</a></p><p>Keeping OPENAI_API_KEY / OPENAI_BASE_URL shows that the provider layer is not tied to a single vendor. But the article and demo use DeepSeek V4 Pro as the main path. If you want a coding-agent plan that can call DeepSeek V4 Pro, take a look at the <a href="https://opencode.ai/go?ref=RRWCDRNFVQ">opencode Go plan</a>.</p><p>The provider uses non-streaming /chat/completions. Day 03 does not implement streaming yet because streaming changes terminal output, error handling, and transcript recording. First we stabilize the boundary of one request and one response. More detailed execution logs can come after Day 07.</p><h3>Implementation Steps</h3><h3>1. Define ChatMessage in the Shared Package</h3><p>File: packages/shared/src/types.ts</p><pre>export type ChatRole = &quot;system&quot; | &quot;user&quot; | &quot;assistant&quot;;</pre><pre>export type ChatMessage = {<br>  role: ChatRole;<br>  content: string;<br>};</pre><p>This lets the app runtime and later shared helpers reuse the same message type.</p><h3>2. Add a Model Provider</h3><p>File: apps/mini-harness/src/model/provider.ts</p><p>Core interface:</p><pre>export type ModelProvider = {<br>  name: string;<br>  chat(messages: ChatMessage[]): Promise&lt;ChatMessage&gt;;<br>};</pre><p>createModelProviderFromEnv() checks environment variables in order:</p><ul><li>If OPENCODE_API_KEY exists: return the opencode Go provider, defaulting to deepseek-v4-pro.</li><li>If there is no opencode key but OPENAI_API_KEY exists: return the OpenAI-compatible fallback provider.</li><li>If neither exists: return the mock provider.</li></ul><p>The real provider sends:</p><pre>{<br>  &quot;model&quot;: &quot;deepseek-v4-pro&quot;,<br>  &quot;messages&quot;: [...],<br>  &quot;temperature&quot;: 0.2<br>}</pre><p>Then it converts choices[0].message.content into the harness&#39;s internal assistant message.</p><h3>3. Upgrade the Run Summary into a Chat Run</h3><p>File: apps/mini-harness/src/agent/run.ts</p><p>On Day 02, createRunSummary returned a fixed scaffold message. On Day 03, it starts building a real conversation:</p><pre>const messages: ChatMessage[] = [<br>  {<br>    role: &quot;system&quot;,<br>    content: systemPrompt,<br>  },<br>  {<br>    role: &quot;user&quot;,<br>    content: input.task,<br>  },<br>];</pre><pre>const assistantMessage = await input.provider.chat(messages);<br>const conversation = [...messages, assistantMessage];</pre><p>The returned result now includes:</p><ul><li>provider</li><li>messages</li><li>assistant message</li><li>a context part containing the full conversation</li></ul><p>That also means --context-report now shows the full conversation, not only the user input.</p><h3>4. Update CLI Output</h3><p>File: apps/mini-harness/src/cli.ts</p><p>The CLI now creates a provider and prints the provider name:</p><pre>[mini-harness] Task: explain what an agent harness is<br>[mini-harness] Model provider: mock<br>[mini-harness] Mock model response:</pre><p>If --transcript is enabled, the JSONL record also includes the provider, messages, context parts, and summary output.</p><h3>Demo</h3><p>The full demo record lives in demos/day-03/README.md in the project repository.</p><p>Default mock provider:</p><pre>npm run dev -- &quot;explain what an agent harness is&quot;</pre><p>Output summary:</p><pre>[mini-harness] Task: explain what an agent harness is<br>[mini-harness] Model provider: mock<br>[mini-harness] Mock model response:</pre><pre>I received the user task: explain what an agent harness is</pre><p>Context report:</p><pre>npm run dev -- --context-report &quot;explain what an agent harness is&quot;</pre><p>The output includes:</p><pre>Context Explorer</pre><pre>System prompt          ~...<br>Tool definitions       ~...<br>Conversation           ~...<br>Total                  ~...</pre><p>Real model call:</p><pre>set -a<br>source .env<br>set +a<br>npm run dev -- &quot;explain what an agent harness is&quot;</pre><h3>What Changed in the System?</h3><p>After Day 03, the CLI has moved from static scaffold output to a minimal chat loop:</p><ul><li>It can construct system/user messages.</li><li>It can get an assistant message from a provider.</li><li>It can run offline when there is no API key.</li><li>It can call DeepSeek V4 Pro through opencode Go when OPENCODE_API_KEY is available.</li><li>The context report and transcript record the full conversation instead of a single task string.</li></ul><p>Still missing:</p><ul><li>streaming output</li><li>tool calls</li><li>multi-step agent loop</li><li>retry/backoff</li><li>token budget trimming</li><li>structured error transcript</li></ul><h3>Problems Encountered</h3><h3>1. Real Models Conflict with Reproducible Demos</h3><p>The code should run immediately after readers clone the project, but real LLM calls depend on external services. The tradeoff here is to use mock by default and only use a real provider when a key is explicitly configured.</p><p>This is not the final product shape, but it works well for a teaching project. Every day’s code increment should be independently verifiable.</p><h3>2. Do Not Overcomplicate the Provider Too Early</h3><p>Today’s ModelProvider has only one method: chat(). It does not include streaming, tool choice, JSON mode, or response metadata yet. The reason is simple: none of those capabilities are needed today.</p><p>The interface should leave room for later, but it should not make us pay for future complexity too early.</p><h3>3. Transcript Is Still Not an Execution Log</h3><p>Today’s transcript is still one summary JSONL line, not the full event log planned for Day 07. For now, it only proves that the key chat run structure can be persisted.</p><h3>Tomorrow</h3><p>Day 04 will implement the Tool Registry.</p><p>At that point, the model context will contain not only system/user/assistant messages, but also tool definitions. The harness will need to answer two questions:</p><ul><li>What tools are available?</li><li>When the model asks to call a tool, how does the runtime find and execute the corresponding handler?</li></ul><p>Originally published at penglei.dev</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a7bb9021f71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Day 02: Harness Project Scaffold]]></title>
            <link>https://medium.com/@penouc/day-02-harness-project-scaffold-bc7252c5e337?source=rss-ab3690ce6e5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc7252c5e337</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <dc:creator><![CDATA[Peng Lei]]></dc:creator>
            <pubDate>Tue, 07 Jul 2026 01:19:16 GMT</pubDate>
            <atom:updated>2026-07-07T01:19:16.804Z</atom:updated>
            <content:encoded><![CDATA[<p>Day 02 of the Mini Coding Agent Harness series: setting up a TypeScript and npm workspaces scaffold with the first runnable CLI surface.</p><h3>Introduction</h3><p>On Day 01, we clarified the boundary of an Agent Harness: the model generates the next step, while the harness organizes the user task, context, tools, safety policy, and execution records.</p><p>Day 02 is where we start writing code. But we are not calling a model yet, and we are not executing real tools yet. Today has one basic but important goal: set up the project scaffold and make a minimal CLI runnable.</p><p>That may sound like setup work, but for a coding agent project, the scaffold is not just a random folder layout. Over the next few days, we will add:</p><ul><li>agent loop</li><li>tool registry</li><li>file tools</li><li>context builder</li><li>transcript logging</li><li>approval and sandbox</li><li>patch editing</li><li>project rules</li></ul><p>Without clear package boundaries and a clear entrypoint, all of that code can quickly collapse into one oversized cli.ts. So the Day 02 goal is to create a TypeScript + npm workspaces project that can keep growing.</p><h3>What Are We Solving Today?</h3><p>Today has four deliverables:</p><ol><li>The repository root is an npm workspace.</li><li>apps/mini-harness is the first runnable CLI app.</li><li>packages/shared contains shared types, logger helpers, and token utilities.</li><li>The CLI supports a few minimal commands:</li></ol><pre>npm run dev -- &quot;hello&quot;<br>npm run dev -- --context-report &quot;read package structure&quot;<br>npm run dev -- --transcript logs/runs/day-02.jsonl &quot;hello&quot;</pre><p>This CLI does not call a real LLM yet. It only accepts a task, prints scaffold status, and optionally prints a simplified context report. This output is a placeholder for the future agent loop: first make the data flow work, then replace the internals step by step.</p><h3>Where Does This Fit in Cursor/Codex?</h3><p>Today we are implementing the outermost <strong>CLI surface</strong> and the most basic runtime shell.</p><p>In products such as Cursor, Codex, and Claude Code, the first thing the user interacts with is not the model. It is the product entrypoint:</p><ul><li>How are CLI arguments parsed?</li><li>Where does the task text enter the system?</li><li>Should a debug report be enabled?</li><li>Should a transcript be written?</li><li>How are workspace modules loaded?</li><li>How is the result of a run returned to the terminal?</li></ul><p>None of these are model capabilities, but they decide whether the harness can reliably carry the features we add later.</p><p>At a high level, Day 02 builds this layer:</p><pre>User<br>  -&gt; CLI surface<br>    -&gt; run summary placeholder<br>    -&gt; context report placeholder<br>    -&gt; transcript placeholder</pre><p>Over the next few days, the run summary placeholder will be replaced by real model calls, tool calls, and the agent loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iLsmfj30VP8W1Wh-eYy0Eg.png" /></figure><p>The image above illustrates the Day 02 flow: the user task enters the CLI surface, the CLI organizes the task through the mini-harness app and shared package inside npm workspaces, and the scaffold produces a run summary, context report, and transcript.</p><h3>Design</h3><h3>1. Separate the App and Shared Package with npm Workspaces</h3><p>The root package.json declares workspaces and common scripts:</p><pre>{<br>  &quot;private&quot;: true,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;workspaces&quot;: [<br>    &quot;packages/*&quot;,<br>    &quot;apps/*&quot;<br>  ],<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;npm run build -w packages/shared &amp;&amp; npm run dev -w apps/mini-harness --&quot;,<br>    &quot;build&quot;: &quot;npm run build --workspaces&quot;,<br>    &quot;typecheck&quot;: &quot;npm run build -w packages/shared &amp;&amp; npm run typecheck -w apps/mini-harness&quot;,<br>    &quot;lint&quot;: &quot;npm run lint --workspaces&quot;<br>  }<br>}</pre><p>There is a small but important detail here: the root dev script builds packages/shared before starting the app. That is because @mini-harness/shared exposes dist/*.js through package exports instead of having the app import source files directly.</p><p>This keeps the boundary between app and shared package closer to a real package boundary, instead of relying only on TypeScript path aliases.</p><h3>2. Keep the CLI Entrypoint Thin</h3><p>apps/mini-harness/src/index.ts does only one thing:</p><pre>import { runCli } from &quot;./cli.js&quot;;</pre><pre>await runCli(process.argv.slice(2));</pre><p>The actual argument parsing and execution logic lives in cli.ts. This keeps the entrypoint reusable. Later, if the same runtime needs to be used by tests, a desktop app, or another interface, index.ts will not have turned into a global script full of side effects.</p><h3>3. Define a Run Summary Before Hardcoding Output</h3><p>Today, createRunSummary is not an agent loop yet. It only returns a stable structure:</p><pre>type RunSummary = {<br>  message: string;<br>  contextParts: ContextPart[];<br>  tools: ToolDefinition[];<br>};</pre><p>This may feel early, but it pays off quickly. Later we will add:</p><ul><li>message history</li><li>tool calls</li><li>tool results</li><li>errors</li><li>latency</li><li>context sources</li></ul><p>If Day 02 scattered output directly across console.log calls, every new module would force us to rewrite the CLI. By wrapping the result first, the CLI can focus on display and persistence.</p><h3>4. Reserve Space for Context Reports and Transcripts</h3><p>Today’s context report only estimates token counts for a few context parts:</p><pre>Context Explorer</pre><pre>System prompt          ~...<br>Tool definitions       ~...<br>Conversation           ~...<br>Total                  ~...</pre><p>It does not solve real context selection yet. But it establishes an important habit: a harness should be able to explain what it is giving to the model.</p><p>Similarly, --transcript currently writes just one JSONL line:</p><pre>{&quot;createdAt&quot;:&quot;...&quot;,&quot;task&quot;:&quot;hello&quot;,&quot;summary&quot;:{...}}</pre><p>Day 07 will expand this into a real execution log. Today we only make the flag and file path work.</p><h3>Implementation Steps</h3><h3>1. Create the Root Workspace</h3><p>The repository root keeps package.json, tsconfig.json, .gitignore, .editorconfig, and documentation directories. Root scripts only coordinate packages; they do not contain business logic.</p><p>Current root scripts:</p><pre>npm run dev<br>npm run build<br>npm run typecheck<br>npm run lint</pre><h3>2. Create the CLI App</h3><p>apps/mini-harness/package.json defines the app scripts:</p><pre>{<br>  &quot;name&quot;: &quot;mini-harness&quot;,<br>  &quot;type&quot;: &quot;module&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;dev&quot;: &quot;tsx src/index.ts&quot;,<br>    &quot;build&quot;: &quot;tsc -p tsconfig.json&quot;,<br>    &quot;typecheck&quot;: &quot;tsc -p tsconfig.json --noEmit&quot;,<br>    &quot;lint&quot;: &quot;tsc -p tsconfig.json --noEmit&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;@mini-harness/shared&quot;: &quot;0.1.0&quot;<br>  }<br>}</pre><p>tsx runs TypeScript during development, while tsc handles builds and type checking.</p><h3>3. Create the Shared Package</h3><p>packages/shared currently contains three basic capabilities:</p><ul><li>logger.ts: scoped CLI logging.</li><li>types.ts: shared types such as ContextPart and ToolDefinition.</li><li>token.ts: a rough token estimation helper.</li></ul><p>The shared package is small for now, but it makes the module boundaries explicit: general types and utilities live in shared, while runtime behavior lives in the app.</p><h3>4. Implement Argument Parsing</h3><p>The Day 02 CLI supports three input shapes:</p><pre>npm run dev -- &quot;hello&quot;<br>npm run dev -- --context-report &quot;read package structure&quot;<br>npm run dev -- --transcript logs/runs/day-02.jsonl &quot;hello&quot;</pre><p>The parsing rules are simple:</p><ul><li>--context-report enables the context report.</li><li>--transcript &lt;path&gt; selects a JSONL output path.</li><li>All remaining arguments are joined into the user task.</li></ul><p>If no task is provided, the CLI prints help and returns a non-zero exit code.</p><h3>5. Register the First Mock Tool</h3><p>There are no real tool calls yet, but the project already has a ToolRegistry:</p><pre>registry.register({<br>  name: &quot;echo&quot;,<br>  description: &quot;Return the provided input. Used as the first mock tool before real file tools exist.&quot;,<br>  inputSchema: {<br>    type: &quot;object&quot;,<br>    properties: {<br>      text: { type: &quot;string&quot; }<br>    },<br>    required: [&quot;text&quot;]<br>  },<br>  handler: (input) =&gt; input<br>});</pre><p>The value of echo is not the feature itself. Its value is that it gives Day 04 a place to expand into a real tool registry with schemas, dispatching, and mock tool execution.</p><h3>Demo</h3><p>Run:</p><pre>npm run dev -- &quot;hello&quot;</pre><p>Expected output:</p><pre>[mini-harness] Task: hello<br>[mini-harness] Scaffold ready. Future days will replace this summary with the real agent loop.</pre><p>Run the context report:</p><pre>npm run dev -- --context-report &quot;read package structure&quot;</pre><p>Expected output:</p><pre>[mini-harness] Task: read package structure<br>[mini-harness] Scaffold ready. Future days will replace this summary with the real agent loop.</pre><pre>Context Explorer</pre><pre>System prompt          ~...<br>Tool definitions       ~...<br>Conversation           ~...<br>Total                  ~...</pre><p>Run transcript logging:</p><pre>npm run dev -- --transcript logs/runs/day-02.jsonl &quot;hello&quot;</pre><p>This appends one JSONL line to the selected file and prints the write path.</p><p>The full demo record lives in demos/day-02/README.md in the project repository.</p><h3>What Changed in the System?</h3><p>After Day 02, this repository is no longer just a collection of articles. It now has the first runnable product slice:</p><ul><li>It can start a CLI from the root script.</li><li>It can accept a user task.</li><li>It can print scoped logs.</li><li>It can list scaffold-stage tool definitions.</li><li>It can output a context report.</li><li>It can append a run summary to a JSONL transcript.</li><li>It can pass basic type checking through npm run typecheck.</li></ul><p>This is not an agent yet, but it is now the shell of an agent harness.</p><h3>Problems Encountered</h3><h3>1. The CLI Does Not Call a Real Model Yet</h3><p>That is intentional. If Day 02 jumped directly into the OpenAI or Anthropic SDK, the article would be distracted by API keys, model parameters, and error handling. Model calls belong in Day 03.</p><h3>2. The Tool Registry Is Only a Reserved Shape</h3><p>We registered echo, but the CLI does not let the model decide whether to call it. Tool calling requires structured model actions, and the agent loop has to own observe/act behavior. Those pieces will be covered in Day 04 and Day 06.</p><h3>3. Token Estimation Is Very Rough</h3><p>Today’s token report is only useful for observing context structure. It is not a serious budgeting system. Real context building and debugging will come in Day 08 and Day 09.</p><h3>Tomorrow</h3><p>Day 03 will replace the static scaffold output with a minimal LLM chat loop.</p><p>The goals are:</p><ul><li>Define model message structures.</li><li>Support system/user/assistant messages.</li><li>Abstract a model provider interface.</li><li>Let the CLI return a real assistant response.</li></ul><p>At that point, mini-harness will move from a runnable shell to the smallest harness that can actually talk to a model.</p><p>Originally published at <a href="https://penglei.dev/">penglei.dev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc7252c5e337" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is an Agent Harness: The Boundary Between Model, Agent, and Harness]]></title>
            <link>https://medium.com/@penouc/what-is-an-agent-harness-the-boundary-between-model-agent-and-harness-75b3909e5188?source=rss-ab3690ce6e5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/75b3909e5188</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[harness-engineering]]></category>
            <dc:creator><![CDATA[Peng Lei]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 14:50:41 GMT</pubDate>
            <atom:updated>2026-07-05T14:50:41.319Z</atom:updated>
            <content:encoded><![CDATA[<p>Day 01 of the Mini Coding Agent Harness series: using real OpenAI and Anthropic API shapes to separate model APIs, agent loops, and the harness around them.</p><p>This is the first article in a 14-day series. We are not writing much code yet. Instead, we are drawing the map first: when we talk about coding agent products such as Cursor, Codex, and Claude Code, are we talking about the model, the agent, or the harness around the model?</p><p>After reading this article, you should be able to separate three things:</p><ul><li>What model APIs from OpenAI and Anthropic actually provide.</li><li>What an agent loop adds on top of ordinary chat and tool calling.</li><li>What engineering responsibilities a coding agent harness must own.</li></ul><p>Over the next 13 days, we will gradually turn the modules in this article into code.</p><h3>What Problem Are We Solving Today?</h3><p>From the outside, products like Cursor, Codex, and Claude Code are easy to describe as “a model that is better at writing code.” But the capability of these products is often determined less by the model itself and more by the system around the model.</p><p>That system is what this article calls an <strong>Agent Harness</strong>.</p><p>It answers questions like:</p><ul><li>How does a one-sentence user task become context that the model can understand?</li><li>When the model wants to read files, search code, run tests, or modify files, who actually executes those actions?</li><li>Can the model directly delete files, access the network, or run shell commands?</li><li>How is intermediate state preserved during a multi-step task?</li><li>When the context grows too large, what should be kept, summarized, or dropped?</li><li>When something goes wrong, how can a developer know which step failed?</li></ul><p>These questions are not solved by the model alone. They are solved by different modules inside the harness:</p><p>QuestionResponsible moduleWhat the first phase will implementHow does a user task become model context?Context BuilderAssemble system prompt, user request, tool definitions, project rules, and relevant file snippetsWho executes file reads, code search, tests, and edits?Tool RuntimeDispatch model tool calls to local functions, shell commands, or a patch executorCan the model delete files, access the network, or run shell?Safety LayerRestrict workspace scope and require approval for file writes and command executionHow is intermediate state preserved?Agent Loop + TranscriptSave model outputs, tool calls, tool results, and final task stateWhat happens when context grows too large?Context BuilderStart with structured context parts and token estimates, then later add retrieval and compressionHow do we debug a failed run?TranscriptRecord key events as JSONL so an agent run can be inspected and replayed</p><p>So on Day 01, we are not rushing into implementation. We are clarifying the boundaries first: <strong>what is the model, what is the agent, and what is the harness?</strong> Each following day will turn one piece of this map into code.</p><h3>Common Interface Shapes</h3><p>Modern LLM products and agent products usually expose several kinds of interfaces. They may all look like “calling a model,” but they sit at different abstraction levels.</p><h3>1. Chat Interface</h3><p>The simplest interface is chat. The caller sends input, and the model returns an assistant response.</p><p>With the OpenAI Responses API, the shape looks roughly like this:</p><pre>import OpenAI from &quot;openai&quot;;</pre><pre>const client = new OpenAI();</pre><pre>const response = await client.responses.create({<br>  model: &quot;gpt-5.5&quot;,<br>  instructions: &quot;You are a concise coding assistant.&quot;,<br>  input: &quot;Explain what this repository does.&quot;,<br>});</pre><pre>console.log(response.output_text);</pre><p>This interface works well for Q&amp;A, explanation, summarization, and text generation. Its key property is: <strong>the model only generates the next response</strong>.</p><p>If you ask:</p><pre>Explain this function.</pre><p>The model itself does not know where “this function” lives. Unless the caller has already placed the code in the context, the model cannot read your filesystem.</p><p>The Anthropic Messages API has the same boundary, just with a different field shape:</p><pre>import Anthropic from &quot;@anthropic-ai/sdk&quot;;</pre><pre>const client = new Anthropic();</pre><pre>const message = await client.messages.create({<br>  model: &quot;claude-opus-4-8&quot;,<br>  max_tokens: 1024,<br>  system: &quot;You are a concise coding assistant.&quot;,<br>  messages: [<br>    {<br>      role: &quot;user&quot;,<br>      content: &quot;Explain what this repository does.&quot;,<br>    },<br>  ],<br>});</pre><pre>console.log(message.content);</pre><p>Whether we call the field input in OpenAI or messages in Anthropic, this is still text in and text out. There is no tool execution and no access to the local codebase.</p><h3>2. Tool Calling Interface</h3><p>The next layer is tool calling. The model can return not only natural language, but also a structured action.</p><p>In the OpenAI Responses API, tool definitions are passed through the tools parameter. Here is a realistic read_file tool definition:</p><pre>const response = await client.responses.create({<br>  model: &quot;gpt-5.5&quot;,<br>  input: &quot;Read README.md and summarize it.&quot;,<br>  tools: [<br>    {<br>      type: &quot;function&quot;,<br>      name: &quot;read_file&quot;,<br>      description: &quot;Read a UTF-8 text file from the current workspace.&quot;,<br>      parameters: {<br>        type: &quot;object&quot;,<br>        properties: {<br>          path: {<br>            type: &quot;string&quot;,<br>            description: &quot;Workspace-relative file path, for example README.md&quot;,<br>          },<br>        },<br>        required: [&quot;path&quot;],<br>        additionalProperties: false,<br>      },<br>    },<br>  ],<br>});</pre><p>If the model decides to use the tool, the response will include an output item similar to function_call. Your program must find that output item, read its name, call_id, and arguments, and then execute the corresponding function. After execution, it sends the result back to the model as function_call_output:</p><pre>const toolResult = await readFileFromWorkspace(&quot;README.md&quot;);</pre><pre>const finalResponse = await client.responses.create({<br>  model: &quot;gpt-5.5&quot;,<br>  input: [<br>    { role: &quot;user&quot;, content: &quot;Read README.md and summarize it.&quot; },<br>    ...response.output,<br>    {<br>      type: &quot;function_call_output&quot;,<br>      call_id: &quot;call_abc123&quot;,<br>      output: toolResult,<br>    },<br>  ],<br>  tools: [<br>    {<br>      type: &quot;function&quot;,<br>      name: &quot;read_file&quot;,<br>      description: &quot;Read a UTF-8 text file from the current workspace.&quot;,<br>      parameters: {<br>        type: &quot;object&quot;,<br>        properties: {<br>          path: { type: &quot;string&quot; },<br>        },<br>        required: [&quot;path&quot;],<br>        additionalProperties: false,<br>      },<br>    },<br>  ],<br>});</pre><p>Anthropic also passes tool definitions at the top level of the request, but the schema field is named input_schema:</p><pre>const message = await client.messages.create({<br>  model: &quot;claude-opus-4-8&quot;,<br>  max_tokens: 1024,<br>  tools: [<br>    {<br>      name: &quot;read_file&quot;,<br>      description: &quot;Read a UTF-8 text file from the current workspace.&quot;,<br>      input_schema: {<br>        type: &quot;object&quot;,<br>        properties: {<br>          path: {<br>            type: &quot;string&quot;,<br>            description: &quot;Workspace-relative file path, for example README.md&quot;,<br>          },<br>        },<br>        required: [&quot;path&quot;],<br>      },<br>    },<br>  ],<br>  messages: [<br>    {<br>      role: &quot;user&quot;,<br>      content: &quot;Read README.md and summarize it.&quot;,<br>    },<br>  ],<br>});</pre><p>If Claude decides to call a tool, the assistant message’s content contains a tool_use block:</p><pre>{<br>  &quot;role&quot;: &quot;assistant&quot;,<br>  &quot;content&quot;: [<br>    {<br>      &quot;type&quot;: &quot;tool_use&quot;,<br>      &quot;id&quot;: &quot;toolu_01...&quot;,<br>      &quot;name&quot;: &quot;read_file&quot;,<br>      &quot;input&quot;: {<br>        &quot;path&quot;: &quot;README.md&quot;<br>      }<br>    }<br>  ]<br>}</pre><p>After your program executes the tool, it sends the result back as a tool_result:</p><pre>const nextMessage = await client.messages.create({<br>  model: &quot;claude-opus-4-8&quot;,<br>  max_tokens: 1024,<br>  tools,<br>  messages: [<br>    {<br>      role: &quot;user&quot;,<br>      content: &quot;Read README.md and summarize it.&quot;,<br>    },<br>    {<br>      role: &quot;assistant&quot;,<br>      content: message.content,<br>    },<br>    {<br>      role: &quot;user&quot;,<br>      content: [<br>        {<br>          type: &quot;tool_result&quot;,<br>          tool_use_id: &quot;toolu_01...&quot;,<br>          content: toolResult,<br>        },<br>      ],<br>    },<br>  ],<br>});</pre><p>The important point is this: the model only emits function_call or tool_use. The model did not actually read the file. The external program did. That external program is the harness.</p><p>This boundary matters:</p><pre>Model decides what tool to call.<br>Harness executes the tool.<br>Model observes the result.</pre><p>The model selects the action. The harness performs the action.</p><h3>3. Agent Loop Interface</h3><p>When tool calling happens more than once, we get an agent loop.</p><p>In the OpenAI Responses API, this usually means maintaining an input array. On each round, you append the previous response.output and tool results, then call client.responses.create(...) again.</p><pre>const input = [{ role: &quot;user&quot; as const, content: &quot;Fix the failing test.&quot; }];</pre><pre>for (let step = 0; step &lt; 8; step += 1) {<br>  const response = await client.responses.create({<br>    model: &quot;gpt-5.5&quot;,<br>    input,<br>    tools,<br>  });</pre><pre>  input.push(...response.output);</pre><pre>  const functionCalls = response.output.filter(<br>    (item) =&gt; item.type === &quot;function_call&quot;,<br>  );</pre><pre>  if (functionCalls.length === 0) {<br>    break;<br>  }</pre><pre>  for (const call of functionCalls) {<br>    const output = await runTool(call.name, call.arguments);<br>    input.push({<br>      type: &quot;function_call_output&quot;,<br>      call_id: call.call_id,<br>      output,<br>    });<br>  }<br>}</pre><p>In the Anthropic Messages API, the same loop revolves around tool_use and tool_result blocks:</p><pre>const messages = [<br>  {<br>    role: &quot;user&quot; as const,<br>    content: &quot;Fix the failing test.&quot;,<br>  },<br>];</pre><pre>for (let step = 0; step &lt; 8; step += 1) {<br>  const message = await client.messages.create({<br>    model: &quot;claude-opus-4-8&quot;,<br>    max_tokens: 4096,<br>    tools,<br>    messages,<br>  });</pre><pre>  messages.push({<br>    role: &quot;assistant&quot;,<br>    content: message.content,<br>  });</pre><pre>  const toolUses = message.content.filter((block) =&gt; block.type === &quot;tool_use&quot;);</pre><pre>  if (toolUses.length === 0) {<br>    break;<br>  }</pre><pre>  messages.push({<br>    role: &quot;user&quot;,<br>    content: await Promise.all(<br>      toolUses.map(async (toolUse) =&gt; ({<br>        type: &quot;tool_result&quot;,<br>        tool_use_id: toolUse.id,<br>        content: await runTool(toolUse.name, toolUse.input),<br>      })),<br>    ),<br>  });<br>}</pre><p>For example, a coding agent fixing a bug might go through these steps:</p><ol><li>Read the error log</li><li>Search for the related function</li><li>Read the implementation file</li><li>Modify the code</li><li>Run tests</li><li>Continue fixing based on test output</li><li>Produce the final summary</li></ol><p>At this point, the product is no longer “one model call.” It needs a loop controller: when to continue, when to stop, and how to recover after failure. This is the core of the harness.</p><p>In other words, OpenAI or Anthropic provides the model API and the tool-calling protocol. Your harness turns those protocols into a reliable engineering execution loop.</p><h3>4. IDE / CLI / App Interface</h3><p>The outermost layer is the product surface that users actually touch.</p><pre>CLI:        codex &quot;fix this bug&quot;<br>IDE:        side panel chat + inline diff<br>Desktop:    task thread + browser + file preview<br>Cloud:      background task + PR + review</pre><p>These surfaces feel very different, but they share the same underlying questions: where does context come from, how do tools run, how are permissions enforced, and how are results shown?</p><p>This series starts with a CLI not because a CLI is the most complete product surface, but because a CLI exposes the essence of the harness with the least UI noise.</p><h3>The Boundary Between Model, Agent, and Harness</h3><p>We can look at the system in three layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Ky1ydgKk3QNI8ScZ7cJHw.png" /></figure><p>In this diagram, the model sits at the bottom as the Model API. It generates responses, reasons about next steps, and chooses tools. It does not directly read or write your filesystem.</p><p>The middle Agent Harness layer is where most product capability comes from. It turns the user task into context, maintains the multi-step loop, executes tools, checks permissions, and records the process.</p><p>The top Product Surface is what the user sees: CLI, IDE extension, desktop app, or cloud task. The experience varies, but the underlying harness problems are similar.</p><p>More concretely:</p><p>LayerIt ownsIt does not ownModelGenerating responses, reasoning, choosing toolsReal file writes, command execution, permission safetyAgentMulti-step task decisionsBreaking system limits or bypassing approvalHarnessTool execution, context management, state persistence, permission controlReplacing model reasoning</p><p>A common misunderstanding is that an agent is a built-in property of the model.</p><p>A more accurate statement is: <strong>agent behavior is produced by combining model capability with an external execution system.</strong></p><p>The model can express the intention “I want to read a file,” but without a read_file tool provided by the harness, it cannot read the file. The model can propose &quot;I should run tests,&quot; but without shell execution in the harness, it cannot run tests. The model can produce a patch, but without a harness applying the diff, the repository does not change.</p><p>This is why the same model can feel completely different in ordinary chat, an IDE extension, a CLI agent, or a cloud task. The difference comes from the harness.</p><h3>What Does a Coding Agent Harness Need?</h3><p>In this series, we will first split the harness into six foundational modules.</p><h3>CLI</h3><p>The CLI is the first product surface. It accepts tasks, parses arguments, and prints results.</p><pre>npm run dev -- &quot;explain this repo&quot;<br>npm run dev -- --context-report &quot;read package structure&quot;</pre><h3>Context Builder</h3><p>The Context Builder decides what the model can see.</p><p>It assembles:</p><ul><li>system prompt</li><li>current user task</li><li>conversation history</li><li>tool definitions</li><li>project rules</li><li>relevant file snippets</li><li>previous tool results</li></ul><p>This is a key capability in a coding agent. Good context makes the model look smart. Bad context makes it get lost.</p><h3>Tool Runtime</h3><p>The Tool Runtime turns model tool calls into real actions.</p><p>For example:</p><pre>read_file({ path: &quot;README.md&quot; })<br>search_text({ query: &quot;ToolRegistry&quot; })<br>git_diff()<br>apply_patch({ patch: &quot;...&quot; })</pre><p>The tool system serves both the model and the program:</p><ul><li>The schema shown to the model must be clear.</li><li>The handler used by the program must be reliable.</li><li>Tool failures must return recoverable errors.</li></ul><h3>Agent Loop</h3><p>The Agent Loop controls a multi-step task.</p><p>It handles:</p><ul><li>maximum step count</li><li>tool call results</li><li>whether the model has reached final output</li><li>timeouts</li><li>error recovery</li><li>intermediate state recording</li></ul><p>Without a loop, you only have a single model call. With a loop, the system starts to behave like an agent.</p><h3>Safety Layer</h3><p>The Safety Layer owns the permission boundary.</p><p>It decides:</p><ul><li>which paths can be read</li><li>which paths can be written</li><li>which commands can run directly</li><li>which actions require user approval</li><li>whether network access is allowed</li></ul><p>The stronger a coding agent becomes, the more important the Safety Layer becomes.</p><h3>Transcript</h3><p>The Transcript is the execution log. It records what happened during a task:</p><ul><li>user input</li><li>model response</li><li>tool call</li><li>tool result</li><li>error</li><li>latency</li></ul><p>Without a transcript, agent failures are hard to debug. You only see the bad result, not why the system reached it.</p><h3>How This Series Will Proceed</h3><p>The first phase of this series is 14 days. The goal is not to build a complete Cursor clone. The goal is to build a CLI harness that explains the core mechanics.</p><p>By the end of this phase, the system should look like this:</p><pre>User task<br>  -&gt; CLI receives it<br>  -&gt; Context Builder assembles context<br>  -&gt; Agent Loop calls the model<br>  -&gt; Tool Runtime reads files, searches, inspects diffs, applies patches<br>  -&gt; Safety Layer asks for approval<br>  -&gt; Transcript records the run<br>  -&gt; final result and debug output are printed</pre><p>The Day 14 acceptance target is:</p><ul><li>the agent can read files</li><li>the agent can search code</li><li>the agent can inspect git diff</li><li>the agent can apply a patch after approval</li><li>the key execution process can be recorded and debugged</li></ul><p>Skills, MCP, IDE extensions, browser control, and subagents belong to the second phase.</p><h3>Demo</h3><p>Day 01 does not implement agent functionality yet, but the demo should still verify something real. Today’s demo checks three things: the article’s main structure exists, the layered architecture image exists, and the project architecture document corresponds to the article.</p><pre>rg -n &quot;^## (Article introduction|Common interface forms|Boundaries between models, agents, and harnesses|What a coding agent harness needs)&quot; articles/day-01-what-is-agent-harness.md<br>file assets/day-01/agent-harness-layers.png<br>sed -n &#39;1,80p&#39; docs/architecture.md</pre><h3>Current System Capability Change</h3><p>Today completed the conceptual boundary, not a functional code feature.</p><p>We clarified:</p><ul><li>The model generates and decides.</li><li>The agent is multi-step task behavior.</li><li>The harness owns context, tools, permissions, state, and interaction.</li><li>Much of the difference between Cursor/Codex-style products comes from the harness, not just the model.</li></ul><h3>Problems Encountered</h3><p>The Day 01 problem was not an implementation bug. The hard part was keeping the boundaries clear.</p><p>There were three concrete tradeoffs:</p><ol><li><strong>Do not explain model APIs as if they were agent products.</strong> OpenAI and Anthropic APIs provide chat, tool calling, and structured tool results, but file reads, command execution, and approval all happen inside the harness.</li><li><strong>Do not expand the scope to IDE/MCP/cloud tasks too early.</strong> Those are important product layers, but they obscure the core execution chain. The first phase uses a CLI to expose the essence.</li><li><strong>Do not write only concepts without a verifiable deliverable.</strong> The Day 01 demo does not fake functionality; it verifies that article structure, architecture document, and layered architecture image exist.</li></ol><p>This tradeoff determines the implementation order: first get the CLI, tools, loop, logs, and safety boundary working; then extend into Skills, MCP, IDE extension, and subagents.</p><h3>Tomorrow</h3><p>Tomorrow is Day 02: Project Scaffold.</p><p>We will initialize TypeScript + npm workspaces, create apps/mini-harness and packages/shared, and make the following command run:</p><pre>npm run dev -- &quot;hello&quot;</pre><h3>References</h3><ul><li><a href="https://platform.openai.com/docs/guides/function-calling">OpenAI Function Calling</a></li><li><a href="https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/overview">Anthropic Tool Use Overview</a></li><li><a href="https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/implement-tool-use">Anthropic Define Tools</a></li></ul><p>Source: <a href="https://penglei.dev/blog/2026-06-25-agent-harness-en/">https://penglei.dev/blog/2026–06–25-agent-harness-en/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75b3909e5188" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[手把手教你从零开始安装 Shadowsocks 服务]]></title>
            <link>https://medium.com/@penouc/%E6%89%8B%E6%8A%8A%E6%89%8B%E6%95%99%E4%BD%A0%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%AE%89%E8%A3%85-shadowsocks-%E6%9C%8D%E5%8A%A1-c7fdeea5572b?source=rss-ab3690ce6e5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7fdeea5572b</guid>
            <category><![CDATA[shadowsocks]]></category>
            <category><![CDATA[vultr-promo-code]]></category>
            <category><![CDATA[vultr]]></category>
            <category><![CDATA[科学上网]]></category>
            <category><![CDATA[翻墙]]></category>
            <dc:creator><![CDATA[Peng Lei]]></dc:creator>
            <pubDate>Fri, 21 Jun 2019 14:08:15 GMT</pubDate>
            <atom:updated>2019-10-14T11:38:30.844Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>如果你还未安装好ss服务，在这篇文章中，将会把整个操作分成4步，大家可以按照我写的这六步操作，最后搭建属于自己的服务。</blockquote><blockquote>如果你已经购买了DO家VPS，请跳转到<a href="https://medium.com/#%E6%90%AD%E5%BB%BAshadowsocks%E6%9C%8D%E5%8A%A1">搭建shadowsocks服务</a></blockquote><blockquote>如果你已经安装好ss服务，需要查看客户端如何配置，跳转到 <a href="https://medium.com/#%E5%AE%89%E8%A3%85shadowsocks%E5%AE%A2%E6%88%B7%E7%AB%AF">安装shadowsocks客户端</a></blockquote><blockquote>文中将会把Shadowsocks简称为ss</blockquote><h4>注册一个VPS</h4><p>首先，我们要选择一家国外的提供商。我使用过的国外的服务有DigtalOcean（后面简称为DO）和vultr。DO被封禁的ip非常的多(树大招风)，当然vultr被封的也有很多，所以在这一个步骤中，你可能需要经历多次操作，才能找到一个稳定可靠的服务。</p><blockquote>以下是<a href="https://www.vultr.com/?ref=7859762-4F">vultr</a>的注册链接，使用此链接您将获得赠送的20美元。</blockquote><p>在chrome浏览器中打开这个链接，你将看到如下的页面</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*EJDjP6NPkm4k7umFfZHi1A.png" /></figure><p>然后你需要点击图中右上角的<strong>Create Account</strong>按钮，进入接下来的页面中，输入你的邮箱地址和密码，你将会跳转到一个你的个人页面</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*CvPqw77oWzwghXlIZEGiow.png" /></figure><p>vultr支持信用卡，paypal和在这个页面中输入你的支付信息。</p><h4>开启一台机器</h4><p>完成上述的操作后，你就拥有完成接下来操作的权利了。</p><p>点击左侧面板上的Servers按钮，进入到了一个选购机器页面的页面</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*FJDAw-zih10ktQ4MdicL0A.png" /></figure><p>如图所示，这里作者推荐日本的机器，北京联通非常的稳定可靠，经历了风风雨雨，目前为止还没有封，机器系统选择Ubuntu14.04（这个是根据个人喜好），但是后面的讲解中使用的命令都是用到Ubuntu的命令，所以推荐小白用户选择此系统，后面还有<strong>Additional Features</strong>, <strong>Startup Script </strong>, <strong>SSH Keys </strong>, <strong>Server Hostname &amp; Label</strong>选项，这些配置各位可以根据自己的需要进行相关的配置，选购完你的机器后就可以deploy你的VPS了。</p><p>等待Servers列表你的机器的Status的状态变成了running状态后，点击该机器，进入机器详细介绍页，如图所示</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*6nBHkzNMf_0huI-0C8eh9Q.png" /></figure><p>此按钮</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ZqWJC74d9m3_UaLYLA6YGw.png" /></figure><p>查看密码</p><p>在你的电脑上打开命令行工具，输入</p><pre>ssh root@你的ip</pre><p>接下来输入你的密码，你就拥有了对这个台VPS的root控制权限了</p><h4>搭建ss服务</h4><p>输入密码后，接着在命令行键入一下命令，开启你的ss服务了</p><p>我们将会安装python版本的shadowsocks，需要先在这台机器上安装pip管理工具</p><pre>apt-get install python-pip</pre><p>当提示如下时</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*2gwpo7GwFYR95HR9nJVPLw.png" /></figure><p>，表示你pip安装成功</p><p>接下来使用pip安装ss</p><pre>pip install shadowsocks</pre><p>当你看到这个画面时</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*bd4e0RoZ7UKybYmP00aXuw.png" /></figure><p>，表示你的ss安装成功</p><p>这时，你可以尝试在命令行中键入ssserver命令，查看是否安装成功，安装成功的话就可以进入下一步的操作。</p><p>开启ss服务有两种方法，一种是通过在命令行中输入参数，如下所示：</p><pre>ssserver -p 8388 -k password -m aes-256-cfb</pre><p>另外一种方法就是通过配置文件启动，先在VPS的/usr/etc/conf/目录下新建一个ss.conf.json文件，写入如下的配置：</p><pre>{<br>	&quot;server&quot;:&quot;my_server_ip&quot;,<br>	&quot;server_port&quot;:8388,<br>	&quot;local_address&quot;: &quot;127.0.0.1&quot;,<br>	&quot;local_port&quot;:1080,<br>	&quot;password&quot;:&quot;mypassword&quot;,<br>	&quot;timeout&quot;:300,<br>	&quot;method&quot;:&quot;aes-256-cfb&quot;,<br>	&quot;fast_open&quot;: false<br>}</pre><p>上述每一个配置文件每个字段的意义如下：</p><p>然后进入你的配置文件的目录，执行以下命令即可</p><pre>ssserver -c ss.conf.json</pre><p>命令启动成功，如果你想在后台运行ss服务，需要输入如下命令</p><pre>ssserver -c ss.conf.json -d start</pre><h4>安装ss客户端</h4><p>因为各个系统繁杂，笔者就不一一推荐了，iOS推荐<a href="https://itunes.apple.com/us/app/surge-web-developer-tool-proxy/id1040100637?mt=8">Surge</a>，<a href="https://itunes.apple.com/us/app/shadowrocket/id932747118?mt=8">Shadowrocket</a>，macOS推荐shadowsocks-gui。具体可以参考<a href="https://shadowsocks.com/client.html"> shadowsocks客户端 </a>，如果大家有什么好的推荐，请在留言中评论。</p><p>本文收录于<a href="http://penouc.com/">penouc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7fdeea5572b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[手把手教你从零开始安装 Shadowsocks 服务]]></title>
            <link>https://medium.com/@penouc/%E6%89%8B%E6%8A%8A%E6%89%8B%E6%95%99%E4%BD%A0%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%AE%89%E8%A3%85-shadowsocks-%E6%9C%8D%E5%8A%A1-cdd34af5fccd?source=rss-ab3690ce6e5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdd34af5fccd</guid>
            <category><![CDATA[vultr-promo-code]]></category>
            <category><![CDATA[shadowsocks]]></category>
            <category><![CDATA[vultr]]></category>
            <category><![CDATA[科学上网]]></category>
            <category><![CDATA[翻墙]]></category>
            <dc:creator><![CDATA[Peng Lei]]></dc:creator>
            <pubDate>Fri, 24 May 2019 08:14:06 GMT</pubDate>
            <atom:updated>2019-05-24T08:14:06.157Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>如果你还未安装好ss服务，在这篇文章中，将会把整个操作分成4步，大家可以按照我写的这六步操作，最后搭建属于自己的服务。</blockquote><blockquote>如果你已经购买了DO家VPS，请跳转到<a href="https://medium.com/#%E6%90%AD%E5%BB%BAshadowsocks%E6%9C%8D%E5%8A%A1">搭建shadowsocks服务</a></blockquote><blockquote>如果你已经安装好ss服务，需要查看客户端如何配置，跳转到 <a href="https://medium.com/#%E5%AE%89%E8%A3%85shadowsocks%E5%AE%A2%E6%88%B7%E7%AB%AF">安装shadowsocks客户端</a></blockquote><blockquote>文中将会把Shadowsocks简称为ss</blockquote><h4>注册一个VPS</h4><p>首先，我们要选择一家国外的提供商。我使用过的国外的服务有DigtalOcean（后面简称为DO）和vultr。DO被封禁的ip非常的多(树大招风)，当然vultr被封的也有很多，所以在这一个步骤中，你可能需要经历多次操作，才能找到一个稳定可靠的服务。</p><blockquote>以下是<a href="https://www.vultr.com/?ref=7859762-4F">vultr</a>的注册链接，使用此链接您将获得赠送的20美元。</blockquote><p>在chrome浏览器中打开这个链接，你将看到如下的页面</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*EJDjP6NPkm4k7umFfZHi1A.png" /></figure><p>然后你需要点击图中右上角的<strong>Create Account</strong>按钮，进入接下来的页面中，输入你的邮箱地址和密码，你将会跳转到一个你的个人页面</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*CvPqw77oWzwghXlIZEGiow.png" /></figure><p>vultr支持信用卡，paypal和在这个页面中输入你的支付信息。</p><h4>开启一台机器</h4><p>完成上述的操作后，你就拥有完成接下来操作的权利了。</p><p>点击左侧面板上的Servers按钮，进入到了一个选购机器页面的页面</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*FJDAw-zih10ktQ4MdicL0A.png" /></figure><p>如图所示，这里作者推荐日本的机器，北京联通非常的稳定可靠，经历了风风雨雨，目前为止还没有封，机器系统选择Ubuntu14.04（这个是根据个人喜好），但是后面的讲解中使用的命令都是用到Ubuntu的命令，所以推荐小白用户选择此系统，后面还有<strong>Additional Features</strong>, <strong>Startup Script </strong>, <strong>SSH Keys </strong>, <strong>Server Hostname &amp; Label</strong>选项，这些配置各位可以根据自己的需要进行相关的配置，选购完你的机器后就可以deploy你的VPS了。</p><p>等待Servers列表你的机器的Status的状态变成了running状态后，点击该机器，进入机器详细介绍页，如图所示</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*6nBHkzNMf_0huI-0C8eh9Q.png" /></figure><p>此按钮</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ZqWJC74d9m3_UaLYLA6YGw.png" /></figure><p>查看密码</p><p>在你的电脑上打开命令行工具，输入</p><pre>ssh root@你的ip</pre><p>接下来输入你的密码，你就拥有了对这个台VPS的root控制权限了</p><h4>搭建ss服务</h4><p>输入密码后，接着在命令行键入一下命令，开启你的ss服务了</p><p>我们将会安装python版本的shadowsocks，需要先在这台机器上安装pip管理工具</p><pre>apt-get install python-pip</pre><p>当提示如下时</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*2gwpo7GwFYR95HR9nJVPLw.png" /></figure><p>，表示你pip安装成功</p><p>接下来使用pip安装ss</p><pre>pip install shadowsocks</pre><p>当你看到这个画面时</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*bd4e0RoZ7UKybYmP00aXuw.png" /></figure><p>，表示你的ss安装成功</p><p>这时，你可以尝试在命令行中键入ssserver命令，查看是否安装成功，安装成功的话就可以进入下一步的操作。</p><p>开启ss服务有两种方法，一种是通过在命令行中输入参数，如下所示：</p><pre>ssserver -p 8388 -k password -m aes-256-cfb</pre><p>另外一种方法就是通过配置文件启动，先在VPS的/usr/etc/conf/目录下新建一个ss.conf.json文件，写入如下的配置：</p><pre>{<br>	&quot;server&quot;:&quot;my_server_ip&quot;,<br>	&quot;server_port&quot;:8388,<br>	&quot;local_address&quot;: &quot;127.0.0.1&quot;,<br>	&quot;local_port&quot;:1080,<br>	&quot;password&quot;:&quot;mypassword&quot;,<br>	&quot;timeout&quot;:300,<br>	&quot;method&quot;:&quot;aes-256-cfb&quot;,<br>	&quot;fast_open&quot;: false<br>}</pre><p>上述每一个配置文件每个字段的意义如下：</p><p>然后进入你的配置文件的目录，执行以下命令即可</p><pre>ssserver -c ss.conf.json</pre><p>命令启动成功，如果你想在后台运行ss服务，需要输入如下命令</p><pre>ssserver -c ss.conf.json -d start</pre><h4>安装ss客户端</h4><p>因为各个系统繁杂，其中配置各不相同，笔者也不能一一覆盖到，就不做推荐，iOS推荐<a href="https://itunes.apple.com/us/app/surge-web-developer-tool-proxy/id1040100637?mt=8">Surge</a>，<a href="https://itunes.apple.com/us/app/shadowrocket/id932747118?mt=8">Shadowrocket</a>，macOS推荐shadowsocks-gui。具体可以参考<a href="https://shadowsocks.com/client.html"> shadowsocks客户端 </a>，也可以通过Google等搜索引擎查询，或者大家如果平时在使用过程中，有使用感受体验比较好可以推荐的，请在留言中评论。</p><p>本文收录于<a href="http://penouc.com/">penouc</a>, 更多技术相关文章请点击链接，查看更多。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdd34af5fccd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[手把手教你从零开始安装 Shadowsocks 服务]]></title>
            <link>https://medium.com/@penouc/%E6%89%8B%E6%8A%8A%E6%89%8B%E6%95%99%E4%BD%A0%E4%BB%8E%E9%9B%B6%E5%BC%80%E5%A7%8B%E5%AE%89%E8%A3%85-shadowsocks-%E6%9C%8D%E5%8A%A1-3bf92d9b0e62?source=rss-ab3690ce6e5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bf92d9b0e62</guid>
            <category><![CDATA[shadowsocks]]></category>
            <category><![CDATA[gfw]]></category>
            <dc:creator><![CDATA[Peng Lei]]></dc:creator>
            <pubDate>Sat, 05 Nov 2016 13:20:15 GMT</pubDate>
            <atom:updated>2019-02-12T10:04:12.632Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>如果你还未安装好ss服务，在这篇文章中，将会把整个操作分成4步，大家可以按照我写的这六步操作，最后搭建属于自己的服务。</blockquote><blockquote>如果你已经购买了DO家VPS，请跳转到<a href="https://medium.com/#%E6%90%AD%E5%BB%BAshadowsocks%E6%9C%8D%E5%8A%A1">搭建shadowsocks服务</a></blockquote><blockquote>如果你已经安装好ss服务，需要查看客户端如何配置，跳转到 <a href="https://medium.com/#%E5%AE%89%E8%A3%85shadowsocks%E5%AE%A2%E6%88%B7%E7%AB%AF">安装shadowsocks客户端</a></blockquote><blockquote>文中将会把Shadowsocks简称为ss</blockquote><h4>注册一个VPS</h4><p>首先，我们要选择一家国外的提供商。我使用过的国外的服务有DigtalOcean（后面简称为DO）和vultr。DO被封禁的ip非常的多(树大招风)，当然vultr被封的也有很多，所以在这一个步骤中，你可能需要经历多次操作，才能找到一个稳定可靠的服务。</p><blockquote>以下是<a href="https://www.vultr.com/?ref=7859762-4F">vultr</a>的注册链接，使用此链接您将获得赠送的 <strong>50 </strong>美元。</blockquote><p>在chrome浏览器中打开这个链接，你将看到如下的页面</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*EJDjP6NPkm4k7umFfZHi1A.png" /></figure><p>然后你需要点击图中右上角的<strong>Create Account</strong>按钮，进入接下来的页面中，输入你的邮箱地址和密码，你将会跳转到一个你的个人页面</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*CvPqw77oWzwghXlIZEGiow.png" /></figure><p>vultr支持信用卡，paypal和在这个页面中输入你的支付信息。</p><h4>开启一台机器</h4><p>完成上述的操作后，你就拥有完成接下来操作的权利了。</p><p>点击左侧面板上的Servers按钮，进入到了一个选购机器页面的页面</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*FJDAw-zih10ktQ4MdicL0A.png" /></figure><p>如图所示，这里作者推荐日本的机器，北京联通非常的稳定可靠，经历了风风雨雨，目前为止还没有封，机器系统选择Ubuntu14.04（这个是根据个人喜好），但是后面的讲解中使用的命令都是用到Ubuntu的命令，所以推荐小白用户选择此系统，后面还有<strong>Additional Features</strong>, <strong>Startup Script </strong>, <strong>SSH Keys </strong>, <strong>Server Hostname &amp; Label</strong>选项，这些配置各位可以根据自己的需要进行相关的配置，选购完你的机器后就可以deploy你的VPS了。</p><p>等待Servers列表你的机器的Status的状态变成了running状态后，点击该机器，进入机器详细介绍页，如图所示</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*6nBHkzNMf_0huI-0C8eh9Q.png" /></figure><p>此按钮</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*ZqWJC74d9m3_UaLYLA6YGw.png" /></figure><p>查看密码</p><p>在你的电脑上打开命令行工具，输入</p><pre>ssh root@你的ip</pre><p>接下来输入你的密码，你就拥有了对这个台VPS的root控制权限了</p><h4>搭建ss服务</h4><p>输入密码后，接着在命令行键入一下命令，开启你的ss服务了</p><p>我们将会安装python版本的shadowsocks，需要先在这台机器上安装pip管理工具</p><pre>apt-get install python-pip</pre><p>当提示如下时</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*2gwpo7GwFYR95HR9nJVPLw.png" /></figure><p>，表示你pip安装成功</p><p>接下来使用pip安装ss</p><pre>pip install shadowsocks</pre><p>当你看到这个画面时</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*bd4e0RoZ7UKybYmP00aXuw.png" /></figure><p>，表示你的ss安装成功</p><p>这时，你可以尝试在命令行中键入ssserver命令，查看是否安装成功，安装成功的话就可以进入下一步的操作。</p><p>开启ss服务有两种方法，一种是通过在命令行中输入参数，如下所示：</p><pre>ssserver -p 8388 -k password -m aes-256-cfb</pre><p>另外一种方法就是通过配置文件启动，先在VPS的/usr/etc/conf/目录下新建一个ss.conf.json文件，写入如下的配置：</p><pre>{<br>	&quot;server&quot;:&quot;my_server_ip&quot;,<br>	&quot;server_port&quot;:8388,<br>	&quot;local_address&quot;: &quot;127.0.0.1&quot;,<br>	&quot;local_port&quot;:1080,<br>	&quot;password&quot;:&quot;mypassword&quot;,<br>	&quot;timeout&quot;:300,<br>	&quot;method&quot;:&quot;aes-256-cfb&quot;,<br>	&quot;fast_open&quot;: false<br>}</pre><p>上述每一个配置文件每个字段的意义如下：</p><p>然后进入你的配置文件的目录，执行以下命令即可</p><pre>ssserver -c ss.conf.json</pre><p>命令启动成功，如果你想在后台运行ss服务，需要输入如下命令</p><pre>ssserver -c ss.conf.json -d start</pre><h4>安装ss客户端</h4><p>因为各个系统繁杂，其中配置各不相同，笔者也不能一一覆盖到，就不做推荐，iOS推荐<a href="https://itunes.apple.com/us/app/surge-web-developer-tool-proxy/id1040100637?mt=8">Surge</a>，<a href="https://itunes.apple.com/us/app/shadowrocket/id932747118?mt=8">Shadowrocket</a>，macOS推荐shadowsocks-gui。具体可以参考<a href="https://shadowsocks.com/client.html"> shadowsocks客户端 </a>，也可以通过Google等搜索引擎查询，或者大家如果平时在使用过程中，有使用感受体验比较好可以推荐的，请在留言中评论。</p><p>本文收录于<a href="http://penouc.com/">penouc</a>, 更多技术相关文章请点击链接，查看更多。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bf92d9b0e62" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[浅谈Javascript数组去重]]></title>
            <link>https://medium.com/@penouc/javascript-7044a9b0d58?source=rss-ab3690ce6e5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7044a9b0d58</guid>
            <dc:creator><![CDATA[Peng Lei]]></dc:creator>
            <pubDate>Thu, 25 Dec 2014 11:11:37 GMT</pubDate>
            <atom:updated>2014-12-25T11:11:37.610Z</atom:updated>
            <content:encoded><![CDATA[<p>刚好前天面试的时候面试官问到了数组去重的问题，当时有点语塞只想到用了两个循环检测（其实模模糊糊想到了hash的方法做但是由于记得不清不敢说= =！），思路是检测是否有元素重复，然后将只出现一次的元素推入到新数组中，然后返回新数组。然后面试官又问这种方法的时间效率，于是黑线了。so这两天看了一下相关的文章，在这里也总结一下javascript数组去重的方法。</p><p>两层循环检测重复元素法</p><p>首先，介绍一下大家都会想到的两层循环的demo，如下例：</p><blockquote><em>function distinct(arr) { var ret = [], length = arr.length; for(var i = 0;i &lt; length; i++){ for(j = i+1; j&lt;length;j++){ if(arr[i] === arr[j]){ j = ++i; } } ret.push(arr[i]); } return ret; } var arra = [1,2,3,4,4,1,1,2,1,1,1]; distinct(arra);</em></blockquote><p>如上的代码实现是轻松易得的，思路如下：</p><ol><li>首先外层循环比遍历整个数组</li><li>内层循环匹配是否有值重复 a.如判断有相同元素则自增i变量，跳出i的循环 b.如判断无时则将无相等值的元素推入到ret数组中<br>3.返回ret。</li></ol><p>优点：便捷易懂，大多数程序员能想到。<br>缺点：很明显时间消耗太高，两层循环时间消耗太多，时间的消耗为O(n^2^)，在进行大量数据处理时会消耗大量资源。而且该方法无法处理字符和数组，如下例:</p><pre>var arr = [1,23,4,5,6,7,’1&#39;,22,3,1,2]; distinct(arr);</pre><p>所以我们可以开始考虑一些别的方法优化数组去重：</p><h2>sort重排数组去除重复元素索引法</h2><p>这种方法就是先讲原数组使用sort方法将数组重排，以得到将相同元素为相邻位的一个新数组。该方法如下：</p><pre>function distinct(arr){ var self = arr; list = self.concat().sort(); list.sort(function(a, b){ if(a === b){ var ind = self.indexOf(a); self.splice(ind, 1); } }); return self; } var arra = [1,2,3,3,1,1,1,’1&#39;]; distinct(arra);</pre><p>同样的，在使用这种方法的重排的时候，仍然会有一定的资源消耗，在sort()函数中回调函数是使用的冒泡排序，而冒泡排序的效率并不高。但是使用这种方法的效率仍然比上一种方法的效率高，因为在此例中只出现了一次循环遍历。</p><p>优点：程序简洁，效率较高。<br>缺点：1.仍然无法解决数字1和字符’1’的去除。2.依赖indexOf方法，我们知道在IE6~8中并未支持indexOf()方法。<br>所以我们还要做一些兼容性的处理。如下:</p><pre>var indexOf = [].indexOf ? function indexOf(arr, item){ return arr.indexOf(item); }: function indexOf(arr, item){ for(var i = 0; i &lt; arr.length; i++){ if(arr[i] === item){ retrun i; } } return -1; } function distinct(arr){ var self = arr; list = self.concat().sort(); list.sort(function(a, b){ if(a === b){ var ind = self.indexOf(arr, a); self.splice(ind, 1); } }); return self; }</pre><p>将数组元素值存为对象的属性</p><pre>function distinct(arr) { var ret = [], json = {}, length = arr.length; for(var i = 0; i &lt; length; i++){ var val = arr[i]; if(!json[val]){ json[val] = 1; ret.push(val); } } return ret; } var arra = [1,2,3,5,7,1,2,’1&#39;];</pre><p>以上方法更加的简洁，而且也能在原来的基础上区分字符‘1’和数字1的区别。<br>在此例中思路如下：<br>1.循环遍历每一个元素<br>2.检测在json对象中是否含遍历到的元素的值 a: 如果是则跳过 b: 如果否存入json对象中该属性名的值设为1<br>3.将存入对象了元素的值推入到新数组中，返回新数组。</p><p>总结，其实数组去重无非就是判断一个元素在数组中是否有重复的值。优化也是一直改变判定元素是否重复的一些技巧，如例1中是遍历数组，例2是重排数组获得索引，例3则别出心裁将元素的值作为对象的属性。</p><p>参考自： <a href="https://github.com/lifesinger/lifesinger.github.com/issues/113">从 JavaScript 数组去重谈性能优化</a> <a href="http://stylechen.com/array-distinct.html">也谈javascript数组去重</a> <a href="http://www.css88.com/archives/2429">js数组去重</a></p><p>同步于个人博客：<a href="http://penxx.pw/">http://penxx.pw</a></p><p>javascript 数组 array 去重 distinct unique</p><p><em>Originally published at </em><a href="http://penxx.pw/2014/05/19/%E6%B5%85%E8%B0%88javascript%E6%95%B0%E7%BB%84%E5%8E%BB%E9%87%8D/"><em>penxx.pw</em></a><em> on May 19, 2014.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7044a9b0d58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS布局总览(1)]]></title>
            <link>https://medium.com/@penouc/css-1-904554fabe90?source=rss-ab3690ce6e5b------2</link>
            <guid isPermaLink="false">https://medium.com/p/904554fabe90</guid>
            <dc:creator><![CDATA[Peng Lei]]></dc:creator>
            <pubDate>Thu, 25 Dec 2014 11:02:20 GMT</pubDate>
            <atom:updated>2014-12-25T11:02:20.573Z</atom:updated>
            <content:encoded><![CDATA[<p>CSS的好处之一是，它能够控制页面布局而不需要使用表现性标记。但是CSS布局被误认为是难以理解的，在初学者当中，这种想法相当普遍。造成这种情况的主要原因是浏览器对CSS的解析不一致导致的。<br>所有的CSS布局技术的根本都是3个基本概念：定位，浮动和外边距操纵。这些布局技术其实没有本质的差异。要掌握它们也不用花很长的时间。</p><p>display属性</p><p>在html中每一个元素都有默认的’display’属性。这与元素的类型有关，对于大多数元素，它们的默认值是inline和block。一个‘block’通常被称作‘块级元素’，而一个‘inline’通常被称作‘行内元素’。</p><p>block</p><pre>div是最常见的标准块级元素。一个块级元素会新开始一行并尽可能的铺满整行的屏幕。其他的常见块级元素有p，form。html5的新元素有header，footer，section等等。</pre><p>inline</p><p>span是一个标准的行内元素，行内元素可以在段落中包裹文字而不打乱段落的布局。a元素是最常用的行内元素，它通常被用作链接。<br>eg:把li元素改成inline，制作水平菜单。</p><p>none</p><p>另一些常用的标记比如script，它的属性就是none。display:none通常被Javascript用来在不删除元素的情况下隐藏或者显示元素。<br>它和visibility属性不一样。display:none不会保留显示本该元素的空间。而visibility:hidden;则会保留该元素的空间。</p><p>inline-block</p><p>很多情况你可能会使用到很多的box填满整个网格,过去我们使用的方法是float属性,但现在使用inline-block,如下两种方法:</p><blockquote>.box { float: left; width: 200px; height: 100px; margin: 1em; } .after-box { clear: left; }</blockquote><blockquote>.box { display: inline-block; width: 200px; height: 100px; margin: 1em; }</blockquote><p>在使用inline-block进行布局的时候要注意以下三点：</p><ol><li>vertical-align会影响到inline-block属性。你可以把它的值设为top。</li><li>你需要设置每一列的宽度</li><li>如果html源代码中标签之间有空格，那么列于列之间会产生间隙。</li></ol><p>如下代码</p><blockquote>nav { display: inline-block; vertical-align: top width: 25%; } .column { display: inline-block; vertical-align: top; width: 75%; }</blockquote><h3>flex</h3><p>新的flex通常被用来使用flex布局，非常的遗憾最近关于flex的变动太多，很多浏览器的实现也不尽相同。所以我简单的介绍一下他们的使用，下面的例子只能在firefox和chrome中实现。</p><blockquote>.container { display: flex; display: -webkit-flex; height: 100px; margin-top: 50px; }</blockquote><blockquote>.one { -webkit-flex: initial; flex: initial; width: 200px; min-width: 100px; }</blockquote><blockquote>.two { -webkit-flex: none; flex: none; width: 200px; }</blockquote><blockquote>.three { -webkit-flex: 1; flex: 1; } .four { -webkit-flex: 2; flex: 2; }</blockquote><p>小屏幕下效果如图</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*f2LuFxwQwTVWBAyd.jpg" /></figure><p>大屏幕下效果如下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qk69dQB-W2xz0aQH.jpg" /></figure><p>flex还可以解决原来css中一个比较让人头痛的问题，就是两盒子的垂直居中。</p><blockquote>body { margin: 0; padding: 0; }</blockquote><blockquote>.big { height: 500px; margin-top: 50px; display: -webkit-flex; display: flex; background-color: #0f0; }</blockquote><blockquote>.small { margin: auto; background-color: #0ff; }</blockquote><p>效果如下图所示:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H3xHs22HRFF0ieau.jpg" /></figure><p>css布局(1)就介绍到这里。</p><p>原文同步于 <a href="http://penxx.pw/">http://penxx.pw</a></p><p>资料来自： <a href="http://http//zh.learnlayout.com/toc.html%E5%92%8C%E3%80%8A%E7%B2%BE%E9%80%9Acss:%E9%AB%98%E7%BA%A7Web%E6%A0%87%E5%87%86%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88%E3%80%8B%E4%B8%80%E4%B9%A6%E7%9A%84%60%E5%B8%83%E5%B1%80%60%E7%AB%A0%E8%8A%82%E3%80%82">http://http://zh.learnlayout.com/toc.html和《精通css:高级Web标准解决方案》一书的`布局`章节。</a></p><p>css 布局 定位 浮动 外边距操纵 display flex</p><p><em>Originally published at </em><a href="http://penxx.pw/2014/05/24/css%E5%B8%83%E5%B1%80%E6%80%BB%E8%A7%88%281%29/"><em>penxx.pw</em></a><em> on May 24, 2014.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=904554fabe90" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>