@cjhyy/code-shell-capability-coding 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/README.md +69 -0
  2. package/THIRD_PARTY_NOTICES.md +206 -0
  3. package/dist/bin/agent-server-stdio.d.ts +1 -0
  4. package/dist/bin/agent-server-stdio.js +4 -0
  5. package/dist/capability-runtime.d.ts +22 -0
  6. package/dist/capability-runtime.js +88 -0
  7. package/dist/cc-orchestrator/agent-adapter.d.ts +55 -0
  8. package/dist/cc-orchestrator/agent-adapter.js +143 -0
  9. package/dist/cc-orchestrator/cc-capability.d.ts +20 -0
  10. package/dist/cc-orchestrator/cc-capability.js +57 -0
  11. package/dist/cc-orchestrator/codex-session-discovery.d.ts +45 -0
  12. package/dist/cc-orchestrator/codex-session-discovery.js +251 -0
  13. package/dist/cc-orchestrator/codex-session-history.d.ts +39 -0
  14. package/dist/cc-orchestrator/codex-session-history.js +249 -0
  15. package/dist/cc-orchestrator/codex-user-text.d.ts +9 -0
  16. package/dist/cc-orchestrator/codex-user-text.js +25 -0
  17. package/dist/cc-orchestrator/external-agent-bindings.d.ts +27 -0
  18. package/dist/cc-orchestrator/external-agent-bindings.js +150 -0
  19. package/dist/cc-orchestrator/external-agent-changes.d.ts +19 -0
  20. package/dist/cc-orchestrator/external-agent-changes.js +231 -0
  21. package/dist/cc-orchestrator/external-agent-driver.d.ts +19 -0
  22. package/dist/cc-orchestrator/external-agent-driver.js +284 -0
  23. package/dist/cc-orchestrator/external-agent-session-store.d.ts +36 -0
  24. package/dist/cc-orchestrator/external-agent-session-store.js +185 -0
  25. package/dist/cc-orchestrator/index.d.ts +10 -0
  26. package/dist/cc-orchestrator/index.js +10 -0
  27. package/dist/cc-orchestrator/related-session-discovery.d.ts +21 -0
  28. package/dist/cc-orchestrator/related-session-discovery.js +77 -0
  29. package/dist/cc-orchestrator/relevance-judge.d.ts +16 -0
  30. package/dist/cc-orchestrator/relevance-judge.js +38 -0
  31. package/dist/cc-orchestrator/session-discovery.d.ts +99 -0
  32. package/dist/cc-orchestrator/session-discovery.js +295 -0
  33. package/dist/cc-orchestrator/session-history.d.ts +55 -0
  34. package/dist/cc-orchestrator/session-history.js +150 -0
  35. package/dist/external-agents/config.d.ts +3 -0
  36. package/dist/external-agents/config.js +16 -0
  37. package/dist/external-agents/types.d.ts +32 -0
  38. package/dist/external-agents/types.js +1 -0
  39. package/dist/external-runtimes/claude-code/event-translator.d.ts +54 -0
  40. package/dist/external-runtimes/claude-code/event-translator.js +201 -0
  41. package/dist/external-runtimes/claude-code/mcp-config.d.ts +84 -0
  42. package/dist/external-runtimes/claude-code/mcp-config.js +175 -0
  43. package/dist/external-runtimes/claude-code/runtime.d.ts +56 -0
  44. package/dist/external-runtimes/claude-code/runtime.js +168 -0
  45. package/dist/external-runtimes/codex/app-server-client.d.ts +66 -0
  46. package/dist/external-runtimes/codex/app-server-client.js +244 -0
  47. package/dist/external-runtimes/codex/event-translator.d.ts +68 -0
  48. package/dist/external-runtimes/codex/event-translator.js +187 -0
  49. package/dist/external-runtimes/codex/index.d.ts +7 -0
  50. package/dist/external-runtimes/codex/index.js +6 -0
  51. package/dist/external-runtimes/codex/runtime.d.ts +128 -0
  52. package/dist/external-runtimes/codex/runtime.js +216 -0
  53. package/dist/external-runtimes/index.d.ts +37 -0
  54. package/dist/external-runtimes/index.js +27 -0
  55. package/dist/external-runtimes/session-factory.d.ts +97 -0
  56. package/dist/external-runtimes/session-factory.js +110 -0
  57. package/dist/external-runtimes/shared/mcp-bridge.d.ts +66 -0
  58. package/dist/external-runtimes/shared/mcp-bridge.js +365 -0
  59. package/dist/external-runtimes/shared/session-context-store.d.ts +83 -0
  60. package/dist/external-runtimes/shared/session-context-store.js +114 -0
  61. package/dist/external-runtimes/shared/spawn-env.d.ts +30 -0
  62. package/dist/external-runtimes/shared/spawn-env.js +41 -0
  63. package/dist/git/parse-log.d.ts +14 -0
  64. package/dist/git/parse-log.js +21 -0
  65. package/dist/git/utils.d.ts +49 -0
  66. package/dist/git/utils.js +161 -0
  67. package/dist/git/worktree/crud.d.ts +108 -0
  68. package/dist/git/worktree/crud.js +415 -0
  69. package/dist/git/worktree/diff.d.ts +14 -0
  70. package/dist/git/worktree/diff.js +83 -0
  71. package/dist/git/worktree/git-exec.d.ts +7 -0
  72. package/dist/git/worktree/git-exec.js +86 -0
  73. package/dist/git/worktree/index.d.ts +6 -0
  74. package/dist/git/worktree/index.js +6 -0
  75. package/dist/git/worktree/query.d.ts +43 -0
  76. package/dist/git/worktree/query.js +128 -0
  77. package/dist/git/worktree/slug.d.ts +12 -0
  78. package/dist/git/worktree/slug.js +59 -0
  79. package/dist/git/worktree.d.ts +1 -0
  80. package/dist/git/worktree.js +5 -0
  81. package/dist/index.capability.d.ts +7 -0
  82. package/dist/index.capability.js +190 -0
  83. package/dist/index.d.ts +18 -0
  84. package/dist/index.git.d.ts +4 -0
  85. package/dist/index.git.js +4 -0
  86. package/dist/index.js +18 -0
  87. package/dist/index.orchestration.d.ts +7 -0
  88. package/dist/index.orchestration.js +5 -0
  89. package/dist/lsp/client.d.ts +41 -0
  90. package/dist/lsp/client.js +192 -0
  91. package/dist/lsp/manager.d.ts +53 -0
  92. package/dist/lsp/manager.js +248 -0
  93. package/dist/lsp/root-path.d.ts +9 -0
  94. package/dist/lsp/root-path.js +12 -0
  95. package/dist/lsp/servers.d.ts +16 -0
  96. package/dist/lsp/servers.js +60 -0
  97. package/dist/prompt/coding.md +42 -0
  98. package/dist/quota/credentials.d.ts +3 -0
  99. package/dist/quota/credentials.js +80 -0
  100. package/dist/quota/index.d.ts +36 -0
  101. package/dist/quota/index.js +161 -0
  102. package/dist/quota/types.d.ts +48 -0
  103. package/dist/quota/types.js +13 -0
  104. package/dist/review/review-prompt.d.ts +28 -0
  105. package/dist/review/review-prompt.js +81 -0
  106. package/dist/tools/apply-patch/LICENSE-codex +201 -0
  107. package/dist/tools/apply-patch/NOTICE.md +29 -0
  108. package/dist/tools/apply-patch/applier.d.ts +26 -0
  109. package/dist/tools/apply-patch/applier.js +306 -0
  110. package/dist/tools/apply-patch/backup-targets.d.ts +10 -0
  111. package/dist/tools/apply-patch/backup-targets.js +30 -0
  112. package/dist/tools/apply-patch/eol.d.ts +4 -0
  113. package/dist/tools/apply-patch/eol.js +9 -0
  114. package/dist/tools/apply-patch/index.d.ts +20 -0
  115. package/dist/tools/apply-patch/index.js +106 -0
  116. package/dist/tools/apply-patch/parser.d.ts +17 -0
  117. package/dist/tools/apply-patch/parser.js +209 -0
  118. package/dist/tools/apply-patch/seek-sequence.d.ts +18 -0
  119. package/dist/tools/apply-patch/seek-sequence.js +123 -0
  120. package/dist/tools/apply-patch/types.d.ts +49 -0
  121. package/dist/tools/apply-patch/types.js +13 -0
  122. package/dist/tools/brief.d.ts +6 -0
  123. package/dist/tools/brief.js +41 -0
  124. package/dist/tools/check-quota.d.ts +14 -0
  125. package/dist/tools/check-quota.js +38 -0
  126. package/dist/tools/drive-agent.d.ts +52 -0
  127. package/dist/tools/drive-agent.js +1184 -0
  128. package/dist/tools/lsp.d.ts +6 -0
  129. package/dist/tools/lsp.js +220 -0
  130. package/dist/tools/notebook-edit.d.ts +6 -0
  131. package/dist/tools/notebook-edit.js +127 -0
  132. package/dist/tools/worktree.d.ts +10 -0
  133. package/dist/tools/worktree.js +363 -0
  134. package/package.json +60 -0
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Coding capability resolver for the tokens `quota/` needs.
3
+ *
4
+ * This is the ONE platform-specific file in the module — it reads a vendor's
5
+ * Keychain entry / auth.json. A host that stores secrets differently (or a
6
+ * future plugin) can bypass this and build QuotaCredentials itself; core logic
7
+ * in index.ts only depends on the QuotaCredentials shape.
8
+ *
9
+ * All reads are best-effort: a missing token yields `undefined`, never a throw,
10
+ * so a machine without Codex or without Keychain access degrades to "quota
11
+ * unavailable for that provider" instead of failing the whole call.
12
+ */
13
+ import { execFile } from "node:child_process";
14
+ import { readFile } from "node:fs/promises";
15
+ import { homedir } from "node:os";
16
+ import { join } from "node:path";
17
+ function userHome() {
18
+ return process.env.HOME || process.env.USERPROFILE || homedir();
19
+ }
20
+ /** Read the Codex OAuth token + account id from ~/.codex/auth.json. */
21
+ async function readCodexCreds() {
22
+ try {
23
+ const raw = await readFile(join(userHome(), ".codex", "auth.json"), "utf8");
24
+ const j = JSON.parse(raw);
25
+ const tokens = (j.tokens ?? {});
26
+ const token = typeof tokens.access_token === "string" ? tokens.access_token : undefined;
27
+ const acct = typeof tokens.account_id === "string" ? tokens.account_id : undefined;
28
+ return { codexAccessToken: token, codexAccountId: acct };
29
+ }
30
+ catch {
31
+ return {};
32
+ }
33
+ }
34
+ /**
35
+ * Read the Claude Code OAuth access token.
36
+ * macOS: Keychain generic-password "Claude Code-credentials".
37
+ * Other platforms: fall back to a plaintext ~/.claude/.credentials.json if present.
38
+ */
39
+ async function readClaudeCreds() {
40
+ // macOS Keychain first.
41
+ if (process.platform === "darwin") {
42
+ const raw = await runSecurity();
43
+ const token = parseClaudeToken(raw);
44
+ if (token)
45
+ return { claudeAccessToken: token };
46
+ }
47
+ // Cross-platform fallback: some installs keep a plaintext credentials file.
48
+ try {
49
+ const raw = await readFile(join(userHome(), ".claude", ".credentials.json"), "utf8");
50
+ const token = parseClaudeToken(raw);
51
+ if (token)
52
+ return { claudeAccessToken: token };
53
+ }
54
+ catch {
55
+ /* not present */
56
+ }
57
+ return {};
58
+ }
59
+ function parseClaudeToken(raw) {
60
+ if (!raw)
61
+ return undefined;
62
+ try {
63
+ const j = JSON.parse(raw);
64
+ const oauth = (j.claudeAiOauth ?? {});
65
+ return typeof oauth.accessToken === "string" ? oauth.accessToken : undefined;
66
+ }
67
+ catch {
68
+ return undefined;
69
+ }
70
+ }
71
+ function runSecurity() {
72
+ return new Promise((resolve) => {
73
+ execFile("security", ["find-generic-password", "-s", "Claude Code-credentials", "-w"], { timeout: 4000 }, (err, stdout) => resolve(err ? null : stdout.toString().trim()));
74
+ });
75
+ }
76
+ /** Resolve all tokens from their standard local locations. Never throws. */
77
+ export async function resolveQuotaCredentials() {
78
+ const [codex, claude] = await Promise.all([readCodexCreds(), readClaudeCreds()]);
79
+ return { ...codex, ...claude };
80
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Coding capability quota for external coding-agent CLIs.
3
+ *
4
+ * Both lookups are verified against the real backends (2026-07-01):
5
+ * - Codex: GET https://chatgpt.com/backend-api/wham/usage → JSON
6
+ * rate_limit.{primary_window,secondary_window}.{used_percent,reset_at}.
7
+ * Zero cost (no message sent).
8
+ * - Claude: POST /v1/messages (max_tokens:1) → response headers
9
+ * anthropic-ratelimit-unified-{5h,7d}-{utilization,reset}.
10
+ * Costs ~1 output token (Claude exposes quota only via response
11
+ * headers — there is no standalone usage endpoint).
12
+ *
13
+ * The `fetch` and credentials are injected so this is unit-testable offline and
14
+ * so the host owns secret resolution (see types.ts boundary note).
15
+ */
16
+ import type { ProviderQuota, QuotaCredentials, QuotaResult } from "./types.js";
17
+ type FetchLike = typeof fetch;
18
+ export interface CheckQuotaOptions {
19
+ creds: QuotaCredentials;
20
+ /** Restrict to specific providers; defaults to both. */
21
+ providers?: ("claude" | "codex")[];
22
+ /** Injected for tests; defaults to global fetch. */
23
+ fetchImpl?: FetchLike;
24
+ /** Caller's abort signal (user Stop); composed with an internal timeout. */
25
+ signal?: AbortSignal;
26
+ timeoutMs?: number;
27
+ }
28
+ /** Codex: GET the usage endpoint and map its JSON to ProviderQuota. */
29
+ export declare function queryCodexQuota(creds: QuotaCredentials, fetchImpl: FetchLike, signal: AbortSignal): Promise<ProviderQuota>;
30
+ /** Claude: POST a 1-token probe and read the unified rate-limit headers. */
31
+ export declare function queryClaudeQuota(creds: QuotaCredentials, fetchImpl: FetchLike, signal: AbortSignal): Promise<ProviderQuota>;
32
+ /** Query both providers (or the subset requested), concurrently. */
33
+ export declare function checkQuota(opts: CheckQuotaOptions): Promise<QuotaResult>;
34
+ /** Render a QuotaResult as a compact human/agent-readable summary. */
35
+ export declare function formatQuota(result: QuotaResult, nowSec: number): string;
36
+ export {};
@@ -0,0 +1,161 @@
1
+ const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
2
+ const CLAUDE_MESSAGES_URL = "https://api.anthropic.com/v1/messages";
3
+ /** Cheapest always-available model for the 1-token probe. */
4
+ const CLAUDE_PROBE_MODEL = "claude-haiku-4-5-20251001";
5
+ const DEFAULT_TIMEOUT_MS = 8000;
6
+ /** Compose the caller signal with a timeout so a hung backend can't block. */
7
+ function withTimeout(signal, timeoutMs) {
8
+ const timeout = AbortSignal.timeout(timeoutMs);
9
+ return signal ? AbortSignal.any([signal, timeout]) : timeout;
10
+ }
11
+ function num(v) {
12
+ const n = typeof v === "string" ? parseFloat(v) : typeof v === "number" ? v : NaN;
13
+ return Number.isFinite(n) ? n : null;
14
+ }
15
+ /** Codex: GET the usage endpoint and map its JSON to ProviderQuota. */
16
+ export async function queryCodexQuota(creds, fetchImpl, signal) {
17
+ if (!creds.codexAccessToken) {
18
+ return { provider: "codex", error: "no Codex token (是否已 codex login?)" };
19
+ }
20
+ let resp;
21
+ try {
22
+ resp = await fetchImpl(CODEX_USAGE_URL, {
23
+ method: "GET",
24
+ headers: {
25
+ authorization: `Bearer ${creds.codexAccessToken}`,
26
+ ...(creds.codexAccountId ? { "chatgpt-account-id": creds.codexAccountId } : {}),
27
+ originator: "codex_cli_rs",
28
+ "user-agent": "codex_cli_rs",
29
+ },
30
+ signal,
31
+ });
32
+ }
33
+ catch (err) {
34
+ return { provider: "codex", error: `请求失败: ${err.message}` };
35
+ }
36
+ if (!resp.ok) {
37
+ return {
38
+ provider: "codex",
39
+ error: `HTTP ${resp.status}${resp.status === 401 ? " (token 可能已过期)" : ""}`,
40
+ };
41
+ }
42
+ let body;
43
+ try {
44
+ body = (await resp.json());
45
+ }
46
+ catch {
47
+ return { provider: "codex", error: "响应非 JSON" };
48
+ }
49
+ const rl = (body.rate_limit ?? {});
50
+ const windows = [];
51
+ const map = [
52
+ ["primary_window", "5h"],
53
+ ["secondary_window", "7d"],
54
+ ];
55
+ for (const [key, kind] of map) {
56
+ const w = rl[key];
57
+ if (!w)
58
+ continue;
59
+ const usedPercent = num(w.used_percent);
60
+ if (usedPercent == null)
61
+ continue;
62
+ windows.push({ kind, usedPercent, resetsAt: num(w.reset_at) });
63
+ }
64
+ if (windows.length === 0)
65
+ return { provider: "codex", error: "响应无 rate_limit 窗口" };
66
+ return {
67
+ provider: "codex",
68
+ windows,
69
+ planType: typeof body.plan_type === "string" ? body.plan_type : null,
70
+ };
71
+ }
72
+ /** Claude: POST a 1-token probe and read the unified rate-limit headers. */
73
+ export async function queryClaudeQuota(creds, fetchImpl, signal) {
74
+ if (!creds.claudeAccessToken) {
75
+ return { provider: "claude", error: "no Claude Code token (是否已登录 Claude Code?)" };
76
+ }
77
+ let resp;
78
+ try {
79
+ resp = await fetchImpl(CLAUDE_MESSAGES_URL, {
80
+ method: "POST",
81
+ headers: {
82
+ authorization: `Bearer ${creds.claudeAccessToken}`,
83
+ "anthropic-version": "2023-06-01",
84
+ "anthropic-beta": "oauth-2025-04-20",
85
+ "content-type": "application/json",
86
+ },
87
+ body: JSON.stringify({
88
+ model: CLAUDE_PROBE_MODEL,
89
+ max_tokens: 1,
90
+ messages: [{ role: "user", content: "hi" }],
91
+ }),
92
+ signal,
93
+ });
94
+ }
95
+ catch (err) {
96
+ return { provider: "claude", error: `请求失败: ${err.message}` };
97
+ }
98
+ if (!resp.ok) {
99
+ return {
100
+ provider: "claude",
101
+ error: `HTTP ${resp.status}${resp.status === 401 ? " (token 可能已过期)" : ""}`,
102
+ };
103
+ }
104
+ const h = resp.headers;
105
+ const windows = [];
106
+ const map = [
107
+ ["anthropic-ratelimit-unified-5h-utilization", "anthropic-ratelimit-unified-5h-reset", "5h"],
108
+ ["anthropic-ratelimit-unified-7d-utilization", "anthropic-ratelimit-unified-7d-reset", "7d"],
109
+ ];
110
+ for (const [utilKey, resetKey, kind] of map) {
111
+ const util = num(h.get(utilKey)); // 0–1
112
+ if (util == null)
113
+ continue;
114
+ windows.push({ kind, usedPercent: util * 100, resetsAt: num(h.get(resetKey)) });
115
+ }
116
+ if (windows.length === 0)
117
+ return { provider: "claude", error: "响应头无 rate-limit 字段" };
118
+ return { provider: "claude", windows };
119
+ }
120
+ /** Query both providers (or the subset requested), concurrently. */
121
+ export async function checkQuota(opts) {
122
+ const fetchImpl = opts.fetchImpl ?? fetch;
123
+ const providers = opts.providers ?? ["claude", "codex"];
124
+ const signal = withTimeout(opts.signal, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS);
125
+ const result = {};
126
+ await Promise.all(providers.map(async (p) => {
127
+ if (p === "codex")
128
+ result.codex = await queryCodexQuota(opts.creds, fetchImpl, signal);
129
+ else
130
+ result.claude = await queryClaudeQuota(opts.creds, fetchImpl, signal);
131
+ }));
132
+ return result;
133
+ }
134
+ /** Render a QuotaResult as a compact human/agent-readable summary. */
135
+ export function formatQuota(result, nowSec) {
136
+ const lines = [];
137
+ for (const pq of [result.claude, result.codex]) {
138
+ if (!pq)
139
+ continue;
140
+ const name = pq.provider === "claude" ? "Claude Code" : "Codex";
141
+ if (pq.error || !pq.windows) {
142
+ lines.push(`${name}: 查询失败 — ${pq.error ?? "unknown"}`);
143
+ continue;
144
+ }
145
+ const plan = pq.planType ? ` [${pq.planType}]` : "";
146
+ const parts = pq.windows.map((w) => {
147
+ const reset = w.resetsAt != null ? ` (重置 ${formatReset(w.resetsAt - nowSec)})` : "";
148
+ return `${w.kind} 用了 ${w.usedPercent.toFixed(0)}%${reset}`;
149
+ });
150
+ lines.push(`${name}${plan}: ${parts.join(",")}`);
151
+ }
152
+ return lines.length ? lines.join("\n") : "(无可用额度信息)";
153
+ }
154
+ /** "2h13m" / "45m" / "已重置" from a seconds delta. */
155
+ function formatReset(deltaSec) {
156
+ if (deltaSec <= 0)
157
+ return "已重置";
158
+ const h = Math.floor(deltaSec / 3600);
159
+ const m = Math.floor((deltaSec % 3600) / 60);
160
+ return h > 0 ? `${h}h${m}m 后` : `${m}m 后`;
161
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Coding-agent quota (rate-limit / usage) types.
3
+ *
4
+ * DESIGN / BOUNDARY NOTE (see project_core_minimal_harness_business_layer):
5
+ * "how to read Claude Code / Codex remaining quota" is provider-specific
6
+ * BUSINESS policy, not core harness mechanism — it pokes a vendor's Keychain
7
+ * entry, an undocumented usage endpoint, and private response headers. It lives
8
+ * in this self-contained `quota/` module (one interface out: `checkQuota`) on
9
+ * purpose, so it can be lifted wholesale into a plugin later without untangling
10
+ * it from the rest of core. Nothing outside this module should know about
11
+ * Keychain / wham endpoints / `anthropic-ratelimit-*` header names.
12
+ */
13
+ /** A single rolling limit window (e.g. the 5-hour or 7-day window). */
14
+ export interface QuotaWindow {
15
+ /** Which window this is. */
16
+ kind: "5h" | "7d";
17
+ /** Percent of the window's limit already used, 0–100. */
18
+ usedPercent: number;
19
+ /** Unix epoch seconds when this window resets, or null if unknown. */
20
+ resetsAt: number | null;
21
+ }
22
+ /** Quota for one provider (claude | codex). */
23
+ export interface ProviderQuota {
24
+ provider: "claude" | "codex";
25
+ /** Present when the lookup succeeded. */
26
+ windows?: QuotaWindow[];
27
+ /** Subscription tier, when the source exposes it (e.g. "team", "pro"). */
28
+ planType?: string | null;
29
+ /** Human-readable failure reason when the lookup did not succeed. */
30
+ error?: string;
31
+ }
32
+ export interface QuotaResult {
33
+ claude?: ProviderQuota;
34
+ codex?: ProviderQuota;
35
+ }
36
+ /**
37
+ * A credential the host supplies so this module can talk to a vendor backend.
38
+ * Core never reads the Keychain / auth.json itself — the host (desktop main /
39
+ * server) resolves the secret and hands it in. This is the seam that makes the
40
+ * whole module portable to a plugin.
41
+ */
42
+ export interface QuotaCredentials {
43
+ /** Claude Code OAuth access token (from Keychain "Claude Code-credentials"). */
44
+ claudeAccessToken?: string;
45
+ /** Codex OAuth access token + account id (from ~/.codex/auth.json). */
46
+ codexAccessToken?: string;
47
+ codexAccountId?: string;
48
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Coding-agent quota (rate-limit / usage) types.
3
+ *
4
+ * DESIGN / BOUNDARY NOTE (see project_core_minimal_harness_business_layer):
5
+ * "how to read Claude Code / Codex remaining quota" is provider-specific
6
+ * BUSINESS policy, not core harness mechanism — it pokes a vendor's Keychain
7
+ * entry, an undocumented usage endpoint, and private response headers. It lives
8
+ * in this self-contained `quota/` module (one interface out: `checkQuota`) on
9
+ * purpose, so it can be lifted wholesale into a plugin later without untangling
10
+ * it from the rest of core. Nothing outside this module should know about
11
+ * Keychain / wham endpoints / `anthropic-ratelimit-*` header names.
12
+ */
13
+ export {};
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Coding capability review-prompt builder. Produces the instruction sent to the
3
+ * model for `/review`. Pure + testable — the TUI/desktop command gathers the
4
+ * diff or file contents and calls this; the model does the actual reasoning.
5
+ *
6
+ * Findings are structured: priority P0–P3, a confidence score, and a precise
7
+ * location, so the output is consistent and (optionally) machine-readable for
8
+ * CI/CD via `--json`.
9
+ */
10
+ export type ReviewDimension = "security" | "performance" | "readability" | "correctness";
11
+ export declare const ALL_DIMENSIONS: ReviewDimension[];
12
+ export interface ReviewPromptOptions {
13
+ /** The unified diff (incremental) or full file contents to review. */
14
+ content: string;
15
+ /** Which dimensions to weigh. Defaults to all four. */
16
+ dimensions?: ReviewDimension[];
17
+ /** True when reviewing a diff (incremental); false when reviewing whole files. */
18
+ incremental?: boolean;
19
+ /** Emit a machine-readable JSON findings array (for CI/CD) instead of prose. */
20
+ json?: boolean;
21
+ /** Optional label for what's under review (e.g. a file path). */
22
+ label?: string;
23
+ /** Truncate content to this many chars (default 12000). */
24
+ maxChars?: number;
25
+ }
26
+ /** Normalize a comma/space list of dimension names; invalid names dropped. */
27
+ export declare function parseDimensions(input: string | undefined): ReviewDimension[];
28
+ export declare function buildReviewPrompt(opts: ReviewPromptOptions): string;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Coding capability review-prompt builder. Produces the instruction sent to the
3
+ * model for `/review`. Pure + testable — the TUI/desktop command gathers the
4
+ * diff or file contents and calls this; the model does the actual reasoning.
5
+ *
6
+ * Findings are structured: priority P0–P3, a confidence score, and a precise
7
+ * location, so the output is consistent and (optionally) machine-readable for
8
+ * CI/CD via `--json`.
9
+ */
10
+ export const ALL_DIMENSIONS = [
11
+ "correctness",
12
+ "security",
13
+ "performance",
14
+ "readability",
15
+ ];
16
+ const DIMENSION_LABEL = {
17
+ security: "安全 (injection, authz, secret leakage, unsafe deserialization)",
18
+ performance: "性能 (N+1, needless allocation, blocking I/O, complexity)",
19
+ readability: "可读性 (naming, structure, dead code, comment accuracy)",
20
+ correctness: "正确性 (logic bugs, edge cases, error handling, races)",
21
+ };
22
+ /** Normalize a comma/space list of dimension names; invalid names dropped. */
23
+ export function parseDimensions(input) {
24
+ if (!input)
25
+ return ALL_DIMENSIONS;
26
+ const wanted = input
27
+ .split(/[\s,]+/)
28
+ .map((s) => s.trim().toLowerCase())
29
+ .filter(Boolean);
30
+ const picked = ALL_DIMENSIONS.filter((d) => wanted.includes(d));
31
+ return picked.length > 0 ? picked : ALL_DIMENSIONS;
32
+ }
33
+ const PRIORITY_GUIDE = "Priority: P0 = must fix before merge (data loss, security hole, crash); " +
34
+ "P1 = should fix (likely bug, real risk); " +
35
+ "P2 = nice to fix (smell, minor inefficiency); " +
36
+ "P3 = optional (style, nit).";
37
+ export function buildReviewPrompt(opts) {
38
+ const dims = opts.dimensions?.length ? opts.dimensions : ALL_DIMENSIONS;
39
+ const maxChars = opts.maxChars ?? 12_000;
40
+ const body = opts.content.length > maxChars
41
+ ? opts.content.slice(0, maxChars) + "\n…(truncated)…"
42
+ : opts.content;
43
+ const fence = opts.incremental === false ? "" : "diff";
44
+ const what = opts.incremental === false ? "code" : "code changes (diff)";
45
+ const subject = opts.label ? ` for \`${opts.label}\`` : "";
46
+ const dimLines = dims.map((d) => ` - ${DIMENSION_LABEL[d]}`).join("\n");
47
+ if (opts.json) {
48
+ return [
49
+ `Review the following ${what}${subject} across these dimensions:`,
50
+ dimLines,
51
+ ``,
52
+ PRIORITY_GUIDE,
53
+ ``,
54
+ `Respond with ONLY a JSON object (no prose, no markdown fence) of the form:`,
55
+ `{"summary": string, "findings": [{"priority": "P0"|"P1"|"P2"|"P3", ` +
56
+ `"dimension": ${dims.map((d) => `"${d}"`).join("|")}, ` +
57
+ `"confidence": number /*0..1*/, "location": string /*file:line*/, ` +
58
+ `"title": string, "detail": string, "suggestion": string}]}`,
59
+ `Order findings by priority then confidence. Omit a finding rather than guess.`,
60
+ ``,
61
+ "```" + fence,
62
+ body,
63
+ "```",
64
+ ].join("\n");
65
+ }
66
+ return [
67
+ `Review the following ${what}${subject} across these dimensions:`,
68
+ dimLines,
69
+ ``,
70
+ PRIORITY_GUIDE,
71
+ ``,
72
+ `For each finding, give: **[P0-P3]** a short title, the location (file:line), ` +
73
+ `your confidence (low/med/high), what's wrong, and a concrete fix.`,
74
+ `Start with a one-line summary, then list findings ordered by priority. ` +
75
+ `If nothing warrants a finding, say so plainly. Don't pad with nits to look thorough.`,
76
+ ``,
77
+ "```" + fence,
78
+ body,
79
+ "```",
80
+ ].join("\n");
81
+ }
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 OpenAI
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.