Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion docs/usage-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -1458,7 +1458,8 @@ Kiro is available as a built-in target. TeamAI deploys skills, rules, and subage
ZCode is available as a built-in target. Skills deploy to `.zcode/skills/` (ZCode also reads the central `~/.agents/skills/`, which the `agents` entry covers), and subagents deploy as Claude-style Markdown to `.zcode/agents/`. Hooks are merged into the shared `~/.zcode/cli/config.json`, preserving unrelated keys such as plugin state. Two ZCode specifics the writer handles for you:

- Config-file hooks are **disabled by default** in ZCode — TeamAI forces `hooks.enabled: true` so the entries it writes actually fire.
- Hook entries use the `process` type (`bash -lc <dispatch>` as an argv vector) rather than a shell string, which sidesteps Windows PATH resolution landing on the WSL `bash.exe` instead of Git Bash.
- On Windows, hook entries launch through a hidden **wscript VBS launcher** (`wscript.exe <teamai-hook-dispatch.vbs> <dispatch tail>`): wscript is a GUI-subsystem binary, so hook runs never flash a console window, and the launcher spools STDIN to a temp file so the payload reaches `hook-dispatch`. Timeouts are network-scale per event (180s session start, 60s stop / prompt submit, 30s post-tool-use) so a session-start dispatch carrying a repo pull is not killed mid-flight. Payloads containing multi-byte text may degrade at the launcher's ANSI-codepage spool step — identity fields are salvaged so degraded dispatches stay linked to the session; uninstall removes both the entries and the script.
- On POSIX, entries are plain `bash -lc <dispatch>` argv vectors and the launcher is not written; on both platforms the command tail is stored verbatim as the entry's last argv element, which is what managed-entry detection and the managed-hooks manifest match against.

These paths are verified against the ZCode desktop app: profiles created in its Subagents settings page land in `~/.zcode/agents/*.md`, and files placed there (e.g. by TeamAI) show up in the page's installed list. MCP servers deploy to `~/.agents/mcp.json` (user scope, Claude `mcpServers` shape — the same file ZCode's own MCP settings page reads). Project scope is not wired: ZCode stores workspace MCP under a different key (`mcp.servers` inside `.zcode/config.json`), which the Claude writer cannot emit. ZCode has no user-level rules directory convention, so rules are not synced.

Expand Down
3 changes: 2 additions & 1 deletion docs/usage-guide.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -1418,7 +1418,8 @@ Kiro 已作为内置目标支持。TeamAI 会将 Skills、Rules 和 Subagents
ZCode 已作为内置目标支持。Skills 下发到 `.zcode/skills/`(ZCode 同时会读取中央目录 `~/.agents/skills/`,该目录由 `agents` 条目覆盖),Subagents 以 Claude 风格 Markdown 下发到 `.zcode/agents/`。Hooks 会合并进共享的 `~/.zcode/cli/config.json`,并保留插件状态等无关键值。写入器为你处理了两个 ZCode 特有的细节:

- ZCode 的配置文件钩子**默认禁用**——TeamAI 会强制置 `hooks.enabled: true`,确保写入的条目真正生效。
- 钩子条目使用 `process` 类型(`bash -lc <dispatch>` 以 argv 向量执行)而非 shell 字符串,规避 Windows 下 PATH 解析命中 WSL `bash.exe` 而非 Git Bash 的陷阱。
- Windows 上,钩子条目通过隐藏的 **wscript VBS 启动器**执行(`wscript.exe <teamai-hook-dispatch.vbs> <分发命令尾段>`):wscript 属 GUI 子系统,钩子运行绝不弹控制台黑框;启动器把 STDIN 暂存为临时文件再转发,保证 payload 完整到达 `hook-dispatch`。超时按事件放宽(会话启动 180 秒、stop / prompt 提交 60 秒、工具调用后 30 秒),避免会话启动时携带仓库拉取的分发被中途掐断。含多字节文本(如中文)的 payload 在启动器的 ANSI 代码页暂存环节可能降级——身份字段会被抢救,降级分发仍能正确关联到会话;卸载时会同时清除条目与脚本文件。
- POSIX 上条目就是普通的 `bash -lc <分发命令尾段>` argv 向量,不写入启动器;两个平台上,命令尾段都以 argv 末位元素原样存储——这正是托管条目识别与托管清单比对的依据。

以上路径已对照 ZCode 桌面端实测验证:设置页「新建子智能体」写入的就是 `~/.zcode/agents/*.md`,反向放入的文件也会出现在页面的已安装列表中。MCP Server 下发到 `~/.agents/mcp.json`(用户级,Claude 的 `mcpServers` 结构——正是 ZCode 自己的 MCP 设置页读取的文件)。项目级暂未接入:ZCode 的工作区 MCP 使用不同的键(`.zcode/config.json` 内的 `mcp.servers`),Claude 写入器无法生成该结构。ZCode 暂无用户级 Rules 目录约定,因此 Rules 不同步。

Expand Down
26 changes: 26 additions & 0 deletions src/__tests__/hook-dispatch-cli.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,32 @@ describe('parseStdin', () => {
expect(Array.isArray(result)).toBe(false);
expect(result).toEqual({ hook_event_name: 'Stop' });
});

it('salvages identity fields from a payload mangled at its multi-byte section', () => {
// Simulates the Windows VBS launcher's ANSI-codepage round trip: the UTF-8
// payload breaks at the first multi-byte sequence (quote swallowed, tail
// lost), but the ASCII head is intact. The degraded dispatch must still be
// linked to the right session and tool.
const mangled =
'{"cwd":"D:\\\\proj","hookEventName":"PostToolUse","sessionId":"sess_abc-123"' +
',"toolName":"Bash","tool_response":{"content":"经验';
const result = parseStdin(mangled, 'post-tool-use');
expect(result.sessionId).toBe('sess_abc-123');
expect(result.toolName).toBe('Bash');
expect(result.cwd).toBe('D:\\proj');
expect(result.hook_event_name).toBe('PostToolUse');
});

it('skips salvage fields whose value itself was truncated mid-string', () => {
// The quote that closes transcript_path was swallowed by the codepage
// round trip, so no intact value exists — the field must be absent rather
// than garbage.
const mangled = '{"sessionId":"sess_ok","transcript_path":"C:\\\\logs\\u4e2d';
const result = parseStdin(mangled, 'stop');
expect(result.sessionId).toBe('sess_ok');
expect(result.transcript_path).toBeUndefined();
expect(result.hook_event_name).toBe('Stop');
});
});
/** A child that reports the given outcome once its listeners are attached. */
function fakePowerShell(code: number | null, error?: Error, output = '') {
Expand Down
88 changes: 83 additions & 5 deletions src/__tests__/zcode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,20 +77,44 @@ describe('ZCode support', () => {
}
expect(hook.type).toBe('process');
if (process.platform === 'win32') {
// Bare `bash` would resolve to the WSL launcher via System32.
expect(hook.command).toBe('cmd');
expect(hook.args?.[0]).toBe('/c');
// wscript.exe is a GUI-subsystem binary — hook runs never flash a
// console window, and the hidden VBS launcher keeps the session
// start non-blocking even while the dispatch pulls over the
// network.
expect(hook.command).toBe('wscript.exe');
expect(hook.args?.[0]).toContain('teamai-hook-dispatch.vbs');
} else {
// POSIX has no console-flash problem: the tail runs directly.
expect(hook.command).toBe('bash');
expect(hook.args?.[0]).toBe('-lc');
}
expect(hook.args?.[1]).toContain('teamai hook-dispatch');
expect(hook.args?.[1]).toContain('--tool zcode');
// The command tail is the LAST argv slot on every platform, stored
// verbatim for managed-entry detection and the manifest.
expect(hook.args?.[hook.args!.length - 1]).toContain('teamai hook-dispatch');
expect(hook.args?.[hook.args!.length - 1]).toContain('--tool zcode');
expect(hook.timeoutMs).toBeGreaterThan(0);
}
}

expect(await getHookStatus(configPath, 'zcode')).toBe('installed');

if (process.platform === 'win32') {
// The launcher script is content-managed: assert the template shipped
// by THIS build — it dispatches Arguments(0) verbatim with no
// hardcoded prefix (a stale prefix doubled the tail and dispatched
// event=teamai; shape-only assertions missed exactly that bug).
const vbs = await fse.readFile(
path.join(path.dirname(configPath), 'teamai-hook-dispatch.vbs'),
'utf-8',
);
expect(vbs).toContain('WScript.Arguments(0)');
expect(vbs).not.toContain('""teamai hook-dispatch');

// A deleted/quarantined launcher must not be reported as installed:
// the entries are dead without the script.
await fse.remove(path.join(path.dirname(configPath), 'teamai-hook-dispatch.vbs'));
expect(await getHookStatus(configPath, 'zcode')).toBe('missing');
}
} finally {
await fse.remove(home);
}
Expand All @@ -113,6 +137,54 @@ describe('ZCode support', () => {
}
});

it('replaces legacy launcher shapes (mode-slot argv) instead of duplicating', async () => {
const home = await fse.mkdtemp(path.join(os.tmpdir(), 'teamai-zcode-test-'));
try {
const configPath = path.join(home, '.zcode', 'cli', 'config.json');
await fse.ensureDir(path.dirname(configPath));
// An entry written by an older generation: [vbsPath, 'wait', tail].
const vbs = path.join(path.dirname(configPath), 'teamai-hook-dispatch.vbs');
await fse.writeJson(configPath, {
hooks: {
enabled: true,
events: {
SessionStart: [
{
hooks: [
{
type: 'process',
command: 'wscript.exe',
args: [vbs, 'wait', 'teamai hook-dispatch session-start --tool zcode'],
timeoutMs: 180000,
},
],
},
],
},
},
});

await reconcileHooks(configPath, 'zcode');

const cfg = await fse.readJson(configPath);
const groups = cfg.hooks.events.SessionStart as Array<{ hooks: Array<{ args?: string[] }> }>;
const withPayload = groups.filter((g) =>
g.hooks[0].args?.some((a) => a?.includes('hook-dispatch session-start')),
);
// The legacy entry must be recognized as managed and replaced, not
// kept alongside a fresh copy. The fresh entry carries the tail as its
// LAST argv slot on every platform ([vbsPath, tail] on win32,
// ['-lc', tail] on POSIX) and no mode slot.
expect(withPayload).toHaveLength(1);
const fresh = withPayload[0].hooks[0].args ?? [];
expect(fresh).toHaveLength(2);
expect(fresh[1]).toBe('teamai hook-dispatch session-start --tool zcode');
expect(fresh.some((a) => a === 'wait')).toBe(false);
} finally {
await fse.remove(home);
}
});

it('removeAll strips teamai entries but keeps the runner and unrelated keys', async () => {
const home = await fse.mkdtemp(path.join(os.tmpdir(), 'teamai-zcode-test-'));
try {
Expand All @@ -133,6 +205,12 @@ describe('ZCode support', () => {
}
expect(await hasTeamaiHooks(configPath, 'zcode')).toBe(false);
expect(await getHookStatus(configPath, 'zcode')).toBe('missing');
// The launcher script must be deleted even when its content matches the
// current template exactly — a content-diff gate would skip it and leave
// the file behind.
expect(
await fse.pathExists(path.join(path.dirname(configPath), 'teamai-hook-dispatch.vbs')),
).toBe(false);
} finally {
await fse.remove(home);
}
Expand Down
65 changes: 60 additions & 5 deletions src/hook-dispatch-cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,60 @@ async function spawnPlainDetached(
}
}

/**
* Identity fields worth salvaging when STDIN JSON cannot be parsed. On Windows
* the hidden VBS launcher decodes the UTF-8 payload through the ANSI codepage,
* so a payload containing multi-byte text can break the JSON structure at the
* first non-ASCII sequence — everything after it is lost, but the ASCII head
* (session id, tool name, paths) is intact and regex-extractable. Salvaging
* keeps a degraded dispatch linked to the right session and tool in the
* dashboard instead of collapsing into an anonymous event. Snake_case and
* camelCase variants are both listed because hosts differ here (ZCode sends
* hookEventName, Claude sends hook_event_name).
*/
const SALVAGEABLE_STDIN_FIELDS = [
'session_id',
'sessionId',
'transcript_path',
'transcriptPath',
'tool_name',
'toolName',
'tool_use_id',
'toolUseId',
'cwd',
] as const;

/** camelCase salvage hits are mirrored onto the snake_case names handlers read. */
const CANONICAL_FIELD_ALIASES: Record<string, string> = {
sessionId: 'session_id',
transcriptPath: 'transcript_path',
toolName: 'tool_name',
toolUseId: 'tool_use_id',
};

/** Extract intact identity fields from an unparsable STDIN body (best-effort). */
export function salvageStdinFields(raw: string): Record<string, string> {
const salvaged: Record<string, string> = {};
for (const field of SALVAGEABLE_STDIN_FIELDS) {
const m = raw.match(new RegExp(`"${field}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`));
if (!m) continue;
try {
salvaged[field] = JSON.parse(`"${m[1]}"`) as string;
} catch {
// A mangled escape inside this field's value — skip it; degraded
// payloads are best-effort by definition.
}
// Handlers read the canonical snake_case names (session_id, tool_name,
// ...) — alias camelCase hits so a salvage from a camelCase host (ZCode)
// still feeds deriveSessionId and the dashboard.
const alias = CANONICAL_FIELD_ALIASES[field];
if (alias && salvaged[field] !== undefined && salvaged[alias] === undefined) {
salvaged[alias] = salvaged[field];
}
}
return salvaged;
}

/**
* Create a detached child through the WMI service instead of CreateProcess.
*
Expand Down Expand Up @@ -291,18 +345,19 @@ export function parseStdin(raw: string, event: string): Record<string, unknown>
try {
stdin = JSON.parse(raw);
} catch {
// Degrade to {} instead of short-circuiting: handlers that depend on
// stdin fields (votes-sync, contribute-check) self-skip when
// transcript_path is absent, while background handlers that don't read
// stdin (version-check, etc.) still get to run. Include a bounded
// preview so concurrent STDIN corruption is diagnosable in debug.log.
// Degrade instead of short-circuiting: handlers that depend on stdin
// fields (votes-sync, contribute-check) self-skip when transcript_path
// is absent, while background handlers that don't read stdin
// (version-check, etc.) still get to run. Include a bounded preview so
// concurrent STDIN corruption is diagnosable in debug.log.
const preview = raw.length > 160
? `${raw.slice(0, 80)}...${raw.slice(-80)}`
: raw;
log.debug(
`hook-dispatch: failed to parse STDIN JSON for event=${event}` +
` (len=${raw.length}, body=${JSON.stringify(preview)})`,
);
stdin = salvageStdinFields(raw);
}
}

Expand Down
Loading
Loading