@geraldmaron/construct 1.2.1 → 1.2.3

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 (208) hide show
  1. package/README.md +6 -6
  2. package/apps/chat/engine/ai-sdk-agent.mjs +183 -0
  3. package/apps/chat/engine/loop-driver.mjs +211 -0
  4. package/apps/chat/engine/models.mjs +122 -0
  5. package/apps/chat/engine/provider-adapters.mjs +171 -0
  6. package/apps/chat/engine/tools/permission.mjs +54 -0
  7. package/apps/chat/engine/tools/primitives.mjs +180 -0
  8. package/apps/chat/engine/tools/registry.mjs +122 -0
  9. package/apps/chat/engine/turn-controls.mjs +70 -0
  10. package/bin/construct +93 -79
  11. package/commands/plan/decide.md +1 -1
  12. package/commands/remember/runbook.md +1 -1
  13. package/examples/README.md +1 -1
  14. package/examples/distribution/README.md +1 -1
  15. package/examples/distribution/sources/adr.md +2 -2
  16. package/examples/distribution/sources/deck-one-pager.md +1 -1
  17. package/examples/distribution/sources/prd-platform.md +1 -1
  18. package/examples/distribution/sources/research-brief.md +2 -2
  19. package/examples/distribution/sources/rfc-platform.md +1 -1
  20. package/examples/distribution/sources/runbook.md +2 -2
  21. package/examples/distribution/sources/strategy.md +1 -1
  22. package/lib/agent-instructions/inject.mjs +1 -1
  23. package/lib/artifact-type-from-path.mjs +9 -5
  24. package/lib/audit-specialists.mjs +1 -1
  25. package/lib/audit-trail.mjs +3 -3
  26. package/lib/auto-docs.mjs +10 -10
  27. package/lib/bootstrap/built-ins.mjs +3 -3
  28. package/lib/boundary.mjs +3 -2
  29. package/lib/brand-prose.mjs +1 -1
  30. package/lib/cache-governor.js +4 -4
  31. package/lib/certification/document-io-fixtures.mjs +1 -1
  32. package/lib/chat/config.mjs +2 -2
  33. package/lib/chat/desktop-binary.mjs +5 -3
  34. package/lib/cli-commands.mjs +4 -6
  35. package/lib/cli-service-inventory.mjs +1 -1
  36. package/lib/comment-lint.mjs +9 -5
  37. package/lib/config/alias.mjs +3 -2
  38. package/lib/config/intake-policy.mjs +8 -78
  39. package/lib/config/legacy-config-migration.mjs +59 -0
  40. package/lib/config/project-config.mjs +95 -5
  41. package/lib/config/schema.mjs +9 -19
  42. package/lib/config/xdg.mjs +63 -0
  43. package/lib/contracts/violation-log.mjs +2 -2
  44. package/lib/cost-ledger.mjs +4 -3
  45. package/lib/cost.mjs +3 -2
  46. package/lib/decisions/registry.mjs +3 -3
  47. package/lib/distill.mjs +2 -2
  48. package/lib/docs-verify.mjs +2 -0
  49. package/lib/doctor/audit.mjs +4 -3
  50. package/lib/doctor/cli.mjs +0 -1
  51. package/lib/doctor/index.mjs +4 -4
  52. package/lib/doctor/report.mjs +3 -3
  53. package/lib/doctor/watchers/bd-watch.mjs +5 -5
  54. package/lib/doctor/watchers/cost.mjs +4 -4
  55. package/lib/doctor/watchers/disk.mjs +4 -3
  56. package/lib/doctor/watchers/service-health.mjs +5 -5
  57. package/lib/document-export.mjs +1 -1
  58. package/lib/document-extract.mjs +3 -3
  59. package/lib/document-ingest.mjs +13 -3
  60. package/lib/efficiency.mjs +2 -1
  61. package/lib/embed/approval-queue.mjs +3 -2
  62. package/lib/embed/cli.mjs +7 -5
  63. package/lib/embed/config.mjs +6 -5
  64. package/lib/embed/daemon.mjs +6 -5
  65. package/lib/embed/inbox-live-watcher.mjs +1 -1
  66. package/lib/embed/inbox.mjs +52 -37
  67. package/lib/embed/intake-metrics.mjs +3 -2
  68. package/lib/embed/reconcile.mjs +1 -1
  69. package/lib/embed/semantic.mjs +3 -2
  70. package/lib/embed/supervision.mjs +4 -2
  71. package/lib/engine/registry.mjs +3 -3
  72. package/lib/env-config.mjs +34 -12
  73. package/lib/features.mjs +4 -3
  74. package/lib/health-check.mjs +7 -6
  75. package/lib/hook-health.mjs +5 -4
  76. package/lib/hooks/_lib/log.mjs +4 -3
  77. package/lib/hooks/_lib/output-mode.mjs +2 -1
  78. package/lib/hooks/agent-tracker.mjs +3 -4
  79. package/lib/hooks/audit-reads.mjs +2 -2
  80. package/lib/hooks/audit-trail.mjs +2 -2
  81. package/lib/hooks/bash-output-logger.mjs +3 -3
  82. package/lib/hooks/brand-prose-lint.mjs +1 -1
  83. package/lib/hooks/ci-status-check.mjs +3 -2
  84. package/lib/hooks/context-watch.mjs +2 -2
  85. package/lib/hooks/context-window-recovery.mjs +5 -5
  86. package/lib/hooks/dep-audit.mjs +2 -2
  87. package/lib/hooks/doc-coupling-check.mjs +3 -2
  88. package/lib/hooks/edit-accumulator.mjs +3 -2
  89. package/lib/hooks/edit-guard.mjs +3 -3
  90. package/lib/hooks/guard-bash.mjs +2 -2
  91. package/lib/hooks/model-fallback.mjs +2 -1
  92. package/lib/hooks/policy-engine.mjs +4 -3
  93. package/lib/hooks/pre-compact.mjs +7 -7
  94. package/lib/hooks/readme-age-check.mjs +2 -2
  95. package/lib/hooks/session-optimize.mjs +4 -3
  96. package/lib/hooks/session-start.mjs +6 -5
  97. package/lib/hooks/stop-notify.mjs +9 -8
  98. package/lib/hooks/stop-typecheck.mjs +4 -3
  99. package/lib/hooks/test-watch.mjs +2 -2
  100. package/lib/host-disposition.mjs +1 -1
  101. package/lib/ingest/provider-extract.mjs +2 -1
  102. package/lib/init/detect-existing-structure.mjs +2 -2
  103. package/lib/init/doc-lanes.mjs +3 -10
  104. package/lib/init-docs.mjs +12 -54
  105. package/lib/init-unified.mjs +35 -81
  106. package/lib/init.mjs +7 -5
  107. package/lib/install/desktop-binary-download.mjs +5 -2
  108. package/lib/intake/daemon.mjs +31 -8
  109. package/lib/intake/intake-config.mjs +5 -32
  110. package/lib/integrations/intake-integrations.mjs +8 -7
  111. package/lib/knowledge/rag.mjs +2 -2
  112. package/lib/knowledge/search.mjs +15 -15
  113. package/lib/maintenance/cleanup.mjs +14 -10
  114. package/lib/mcp/server.mjs +1 -1
  115. package/lib/mcp/tools/project.mjs +2 -1
  116. package/lib/model-cheapest-provider.mjs +4 -3
  117. package/lib/model-pricing.mjs +3 -2
  118. package/lib/model-router.mjs +4 -3
  119. package/lib/models/catalog.mjs +2 -1
  120. package/lib/models/execution-capability-profile.mjs +2 -1
  121. package/lib/models/provider-poll.mjs +2 -1
  122. package/lib/ollama-manager.mjs +0 -1
  123. package/lib/op-log.mjs +2 -1
  124. package/lib/opencode-runtime-plugin.mjs +3 -2
  125. package/lib/oracle/artifact-gate.mjs +3 -0
  126. package/lib/oracle/cli.mjs +2 -1
  127. package/lib/oracle/execute.mjs +3 -2
  128. package/lib/oracle/index.mjs +2 -1
  129. package/lib/oracle/read-model.mjs +3 -2
  130. package/lib/performance/generate.mjs +4 -3
  131. package/lib/platforms/capabilities.mjs +1 -1
  132. package/lib/plugin-registry.mjs +2 -1
  133. package/lib/profiles/lifecycle.mjs +3 -3
  134. package/lib/project-profile.mjs +2 -1
  135. package/lib/project-root.mjs +9 -7
  136. package/lib/provider-capabilities.js +4 -3
  137. package/lib/providers/auth-manager.mjs +2 -1
  138. package/lib/providers/copilot-auth.mjs +3 -2
  139. package/lib/providers/creds.mjs +3 -2
  140. package/lib/providers/registry.mjs +3 -3
  141. package/lib/providers/secret-resolver.mjs +3 -2
  142. package/lib/read-tracker-store.mjs +2 -1
  143. package/lib/reconcile/mcp-entry-reconcile.mjs +2 -2
  144. package/lib/reflect.mjs +2 -1
  145. package/lib/registry/generate-docs.mjs +2 -2
  146. package/lib/roles/approval-surface.mjs +5 -4
  147. package/lib/roles/event-bus.mjs +0 -1
  148. package/lib/roles/gateway.mjs +6 -2
  149. package/lib/rules-delivery.mjs +1 -1
  150. package/lib/runtime-env.mjs +1 -1
  151. package/lib/runtime-pressure.mjs +5 -3
  152. package/lib/sandbox.mjs +3 -2
  153. package/lib/scheduler/solo.mjs +6 -4
  154. package/lib/server/auth.mjs +4 -3
  155. package/lib/server/index.mjs +24 -26
  156. package/lib/server/insights.mjs +5 -4
  157. package/lib/server/webhook.mjs +2 -1
  158. package/lib/service-manager.mjs +5 -3
  159. package/lib/setup.mjs +21 -11
  160. package/lib/status.mjs +6 -5
  161. package/lib/storage/embeddings-local.mjs +3 -2
  162. package/lib/storage/sync.mjs +2 -2
  163. package/lib/telemetry/client.mjs +0 -1
  164. package/lib/telemetry/intent-verifications.mjs +6 -6
  165. package/lib/telemetry/model-pricing-catalog.mjs +4 -3
  166. package/lib/telemetry/rule-calls.mjs +3 -3
  167. package/lib/telemetry/skill-calls.mjs +3 -3
  168. package/lib/template-registry.mjs +1 -0
  169. package/lib/templates/visual-requirements.mjs +1 -1
  170. package/lib/test-corpus-inventory.mjs +1 -1
  171. package/lib/uninstall/uninstall.mjs +12 -10
  172. package/package.json +4 -3
  173. package/platforms/claude/settings.template.json +43 -43
  174. package/rules/common/no-fabrication.md +1 -1
  175. package/rules/common/release-gates.md +1 -1
  176. package/rules/common/research.md +1 -1
  177. package/rules/common/review-before-change.md +1 -1
  178. package/scripts/sync-specialists.mjs +11 -8
  179. package/skills/docs/adr-workflow.md +3 -3
  180. package/skills/docs/init-docs.md +9 -9
  181. package/skills/docs/prd-workflow.md +5 -5
  182. package/skills/docs/product-intelligence-review.md +1 -1
  183. package/skills/docs/product-intelligence-workflow.md +2 -2
  184. package/skills/docs/product-signal-workflow.md +1 -1
  185. package/skills/docs/runbook-workflow.md +4 -4
  186. package/skills/exploration/unknown-codebase-onboarding.md +1 -1
  187. package/skills/operating/orchestration-reference.md +1 -1
  188. package/skills/routing.md +3 -3
  189. package/specialists/prompts/cx-architect.md +1 -1
  190. package/specialists/prompts/cx-docs-keeper.md +1 -1
  191. package/specialists/prompts/cx-researcher.md +1 -1
  192. package/specialists/prompts/cx-sre.md +1 -1
  193. package/specialists/role-manifests.json +6 -6
  194. package/templates/docs/README.md +125 -0
  195. package/templates/docs/construct_guide.md +3 -4
  196. package/templates/docs/persona-artifact.md +1 -1
  197. package/templates/docs/prds/README.md +25 -0
  198. package/templates/docs/prds/templates/_template.md +206 -0
  199. package/templates/docs/prds/templates/meta-prd.template.md +177 -0
  200. package/templates/docs/prds/templates/prd-business.template.md +61 -0
  201. package/templates/docs/prds/templates/prd-platform.template.md +81 -0
  202. package/templates/docs/prds/templates/prfaq.template.md +38 -0
  203. package/templates/docs/rfcs/README.md +22 -0
  204. package/templates/docs/rfcs/templates/_template.md +58 -0
  205. package/templates/docs/rfcs/templates/rfc-platform.template.md +72 -0
  206. package/templates/homebrew/construct.rb +1 -1
  207. package/templates/workflows/new-feature.yml +8 -8
  208. package/lib/intake/legacy-paths.mjs +0 -5
@@ -0,0 +1,171 @@
1
+ /**
2
+ * apps/chat/engine/provider-adapters.mjs — centralized provider execution adapters
3
+ * (construct-6zga.1.3).
4
+ *
5
+ * One registry, keyed by provider group, owns provider execution. Each adapter
6
+ * owns its own credential resolution, base URL, native model-id translation, auth
7
+ * scheme, and AI SDK provider construction; the dispatcher does no
8
+ * provider/model-prefix behavior branch — it extracts the structural provider
9
+ * group (the model id's first segment, the same identity lib/models keys on) and
10
+ * looks the adapter up. Adding a compatible provider is a registry entry plus
11
+ * matrix fixtures, never a dispatch edit.
12
+ *
13
+ * Public model ids are preserved: the native id handed to the SDK is the model id
14
+ * with its group segment stripped, so anthropic/claude-x → claude-x and
15
+ * openrouter/anthropic/claude-x → anthropic/claude-x (OpenRouter's own id).
16
+ * Credentials resolve through the shared secret resolver (env, dotenv, shell rc,
17
+ * 1Password op:// refs); a missing key fails fast with a remediation hint.
18
+ */
19
+ import { resolveFirstSecret } from '../../../lib/providers/secret-resolver.mjs';
20
+ import { providerGroupForModel } from '../../../lib/models/execution-capability-profile.mjs';
21
+
22
+ const OPENROUTER_BASE = 'https://openrouter.ai/api/v1';
23
+
24
+ function envKey(env, ...names) {
25
+ return resolveFirstSecret(names, { env });
26
+ }
27
+
28
+ function missingKey(provider, varName) {
29
+ const err = new Error(`No credentials for ${provider}: set ${varName} (or run \`construct creds\`) and retry.`);
30
+ err.code = 'PROVIDER_KEY_MISSING';
31
+ return err;
32
+ }
33
+
34
+ // Adapter descriptors. `describe` is the serializable contract (auth scheme,
35
+ // protocol, credential env, base URL source) for tracing and conformance fixtures;
36
+ // `createModel` builds the AI SDK handle from the native id. The @ai-sdk/* imports
37
+ // stay lazy so the zero-dep core never loads them.
38
+
39
+ const ADAPTERS = {
40
+ anthropic: {
41
+ id: 'anthropic',
42
+ auth: 'api_key',
43
+ protocol: 'anthropic-messages',
44
+ credentialEnv: ['ANTHROPIC_API_KEY'],
45
+ baseURL: 'default',
46
+ async createModel({ nativeModelId, env }) {
47
+ const apiKey = envKey(env, 'ANTHROPIC_API_KEY');
48
+ if (!apiKey) throw missingKey('Anthropic', 'ANTHROPIC_API_KEY');
49
+ const { createAnthropic } = await import('@ai-sdk/anthropic');
50
+ return createAnthropic({ apiKey })(nativeModelId);
51
+ },
52
+ },
53
+ openai: {
54
+ id: 'openai',
55
+ auth: 'api_key',
56
+ protocol: 'openai-chat-completions',
57
+ credentialEnv: ['OPENAI_API_KEY'],
58
+ baseURL: 'default',
59
+ async createModel({ nativeModelId, env }) {
60
+ const apiKey = envKey(env, 'OPENAI_API_KEY');
61
+ if (!apiKey) throw missingKey('OpenAI', 'OPENAI_API_KEY');
62
+ const { createOpenAI } = await import('@ai-sdk/openai');
63
+ return createOpenAI({ apiKey })(nativeModelId);
64
+ },
65
+ },
66
+ openrouter: {
67
+ id: 'openrouter',
68
+ auth: 'api_key',
69
+ protocol: 'openai-compatible',
70
+ credentialEnv: ['OPENROUTER_API_KEY', 'OPEN_ROUTER_API_KEY'],
71
+ baseURL: OPENROUTER_BASE,
72
+ async createModel({ nativeModelId, env }) {
73
+ const apiKey = envKey(env, 'OPENROUTER_API_KEY', 'OPEN_ROUTER_API_KEY');
74
+ if (!apiKey) throw missingKey('OpenRouter', 'OPENROUTER_API_KEY');
75
+ const { createOpenAICompatible } = await import('@ai-sdk/openai-compatible');
76
+ return createOpenAICompatible({ name: 'openrouter', baseURL: OPENROUTER_BASE, apiKey })(nativeModelId);
77
+ },
78
+ },
79
+ ollama: {
80
+ id: 'ollama',
81
+ auth: 'none',
82
+ protocol: 'openai-compatible',
83
+ credentialEnv: [],
84
+ baseURL: 'env:OLLAMA_BASE_URL',
85
+ async createModel({ modelId, nativeModelId, env }) {
86
+ const { isOllamaModelInstalled, formatOllamaModelMissingMessage } = await import('../../../lib/ollama/installed-models.mjs');
87
+ if (isOllamaModelInstalled(modelId, { env }) === false) {
88
+ const err = new Error(formatOllamaModelMissingMessage(nativeModelId));
89
+ err.code = 'OLLAMA_MODEL_NOT_PULLED';
90
+ throw err;
91
+ }
92
+ const baseURL = envKey(env, 'OLLAMA_BASE_URL') || 'http://localhost:11434/v1';
93
+ const { createOpenAICompatible } = await import('@ai-sdk/openai-compatible');
94
+ return createOpenAICompatible({ name: 'ollama', baseURL, apiKey: 'ollama' })(nativeModelId);
95
+ },
96
+ },
97
+ local: {
98
+ id: 'local',
99
+ auth: 'api_key',
100
+ protocol: 'openai-compatible',
101
+ credentialEnv: ['LOCAL_LLM_API_KEY'],
102
+ baseURL: 'env:LOCAL_LLM_BASE_URL',
103
+ async createModel({ nativeModelId, env }) {
104
+ const baseURL = envKey(env, 'LOCAL_LLM_BASE_URL');
105
+ if (!baseURL) throw missingKey('local OpenAI-compatible server', 'LOCAL_LLM_BASE_URL');
106
+ const { createOpenAICompatible } = await import('@ai-sdk/openai-compatible');
107
+ return createOpenAICompatible({ name: 'local', baseURL, apiKey: envKey(env, 'LOCAL_LLM_API_KEY') || 'local' })(nativeModelId);
108
+ },
109
+ },
110
+ 'github-copilot': {
111
+ id: 'github-copilot',
112
+ auth: 'oauth',
113
+ protocol: 'openai-chat-completions',
114
+ credentialEnv: [],
115
+ baseURL: 'copilot',
116
+ async createModel({ nativeModelId }) {
117
+ const { getCopilotToken, copilotApiHeaders, COPILOT_API_BASE } = await import('../../../lib/providers/copilot-auth.mjs');
118
+ const { createOpenAICompatible } = await import('@ai-sdk/openai-compatible');
119
+ const copilotFetch = async (url, init = {}) => {
120
+ const token = await getCopilotToken();
121
+ const headers = new Headers(init.headers);
122
+ for (const [key, value] of Object.entries(copilotApiHeaders())) headers.set(key, value);
123
+ headers.set('Authorization', `Bearer ${token}`);
124
+ return fetch(url, { ...init, headers });
125
+ };
126
+ return createOpenAICompatible({ name: 'github-copilot', baseURL: COPILOT_API_BASE, apiKey: 'via-fetch', fetch: copilotFetch })(nativeModelId);
127
+ },
128
+ },
129
+ };
130
+
131
+ export function getProviderAdapter(group) {
132
+ return ADAPTERS[group] || null;
133
+ }
134
+
135
+ // Serializable adapter contract for tracing and conformance fixtures (no secrets,
136
+ // no SDK handles) — the metadata a new provider must register.
137
+
138
+ export function describeProviderAdapters() {
139
+ return Object.values(ADAPTERS).map((a) => ({
140
+ id: a.id,
141
+ auth: a.auth,
142
+ protocol: a.protocol,
143
+ credentialEnv: a.credentialEnv,
144
+ baseURL: a.baseURL,
145
+ }));
146
+ }
147
+
148
+ export function nativeModelId(modelId, group = providerGroupForModel(modelId)) {
149
+ return String(modelId).slice(group.length + 1);
150
+ }
151
+
152
+ /**
153
+ * Map a Construct "provider/model" id onto an AI SDK language model via the
154
+ * adapter registry. No provider/model-prefix behavior branch: the group is a
155
+ * structural key, the adapter owns the behavior.
156
+ */
157
+ export async function resolveLanguageModel(modelId, env) {
158
+ if (!modelId) {
159
+ const err = new Error('No model selected and no configured provider found. Run `construct models` or set CX_MODEL_STANDARD.');
160
+ err.code = 'PROVIDER_MODEL_UNRESOLVED';
161
+ throw err;
162
+ }
163
+ const group = providerGroupForModel(modelId);
164
+ const adapter = ADAPTERS[group];
165
+ if (!adapter) {
166
+ const err = new Error(`Provider for model '${modelId}' is not wired into the owned loop yet. Try an anthropic/, openai/, openrouter/, ollama/, local/, or github-copilot/ model.`);
167
+ err.code = 'PROVIDER_UNSUPPORTED';
168
+ throw err;
169
+ }
170
+ return adapter.createModel({ modelId, nativeModelId: nativeModelId(modelId, group), env });
171
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * apps/chat/engine/tools/permission.mjs — the permission and sandbox gate for the
3
+ * owned loop's tools.
4
+ *
5
+ * Owning the loop means Construct, not a host, decides whether a tool runs. This
6
+ * gate reuses the host-agnostic decision vocabulary ADR-0040 defined
7
+ * (allow | allow_always | reject) and the sandbox levels from lib/chat/config.mjs
8
+ * (read-only, workspace-write, danger-full-access). Read-only tools (read, grep,
9
+ * glob) always pass; mutating tools (write, edit, shell) are gated by the sandbox
10
+ * level and the current permission mode, deferring to an interactive
11
+ * `requestPermission` handler only in `ask` mode. `allow_always` is sticky for the
12
+ * rest of the session so a user is not re-prompted per call.
13
+ *
14
+ * `allowOutside` (escape the workspace root) is granted only under
15
+ * danger-full-access; every other level keeps tools inside the workspace, which
16
+ * the primitives enforce independently.
17
+ */
18
+
19
+ export const READ_ONLY_TOOLS = new Set(['read', 'grep', 'glob']);
20
+ export const MUTATING_TOOLS = new Set(['write', 'edit', 'shell']);
21
+
22
+ export function createPermissionGate({
23
+ getSandbox = () => null,
24
+ getPermissionMode = () => 'allow_once',
25
+ requestPermission = null,
26
+ } = {}) {
27
+ let alwaysAllowed = false;
28
+
29
+ async function check(toolName, input = {}) {
30
+ const sandbox = getSandbox() || 'workspace-write';
31
+ const allowOutside = sandbox === 'danger-full-access';
32
+
33
+ if (READ_ONLY_TOOLS.has(toolName)) return { allowed: true, allowOutside };
34
+
35
+ if (sandbox === 'read-only') {
36
+ return { allowed: false, allowOutside, reason: 'sandbox is read-only; mutating tools are disabled (change with /set sandbox workspace-write)' };
37
+ }
38
+
39
+ if (alwaysAllowed) return { allowed: true, allowOutside };
40
+
41
+ const mode = getPermissionMode() || 'allow_once';
42
+ if (mode === 'reject') return { allowed: false, allowOutside, reason: 'permission mode is reject' };
43
+ if (mode === 'allow_always') { alwaysAllowed = true; return { allowed: true, allowOutside }; }
44
+ if (mode === 'allow_once') return { allowed: true, allowOutside };
45
+
46
+ // ask mode: defer to the interactive handler, mapping its decision back.
47
+ const decision = requestPermission ? await requestPermission({ tool: toolName, input }) : 'allow';
48
+ if (decision === 'reject') return { allowed: false, allowOutside, reason: 'denied by user' };
49
+ if (decision === 'allow_always') { alwaysAllowed = true; return { allowed: true, allowOutside }; }
50
+ return { allowed: true, allowOutside };
51
+ }
52
+
53
+ return { check, get alwaysAllowed() { return alwaysAllowed; } };
54
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * apps/chat/engine/tools/primitives.mjs — zero-dep executors for the owned loop's
3
+ * agent tools (read, write, edit, glob, grep, shell).
4
+ *
5
+ * These are the side-effecting primitives the loop calls; they are pure Node so
6
+ * they are fully testable in a tmpdir with no model, network, or SDK. Path safety
7
+ * is enforced here: every path resolves inside the workspace root unless the caller
8
+ * passes `allowOutside` (set only by the danger-full-access sandbox). Search tools
9
+ * walk the tree with a hard result/size cap and skip the usual heavy/ignored dirs
10
+ * so a grep never hangs the loop. Shell reuses the bounded worker runner
11
+ * (lib/worker/run.mjs) for the timeout + path policy already proven there.
12
+ *
13
+ * Every function returns a structured, JSON-serializable result (never throws for
14
+ * an ordinary "not found"/"no match" outcome) so the result maps cleanly onto a
15
+ * tool_update event and back to the model.
16
+ */
17
+
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+ import { randomUUID } from 'node:crypto';
21
+ import { runJob } from '../../../../lib/worker/run.mjs';
22
+
23
+ const IGNORED_DIRS = new Set(['node_modules', '.git', '.cx', 'dist', 'build', '.next', 'coverage', '.cache']);
24
+ const MAX_READ_BYTES = 256 * 1024;
25
+ const MAX_WALK_FILES = 20000;
26
+
27
+ function resolveInside(cwd, target, { allowOutside = false } = {}) {
28
+ const root = path.resolve(cwd);
29
+ const resolved = path.resolve(root, target || '.');
30
+ if (!allowOutside && resolved !== root && !resolved.startsWith(`${root}${path.sep}`)) {
31
+ const err = new Error(`path '${target}' is outside the workspace; not permitted under the current sandbox`);
32
+ err.code = 'PATH_OUTSIDE_WORKSPACE';
33
+ throw err;
34
+ }
35
+ return resolved;
36
+ }
37
+
38
+ export function readFileTool({ cwd, path: target, maxBytes = MAX_READ_BYTES, allowOutside = false } = {}) {
39
+ const file = resolveInside(cwd, target, { allowOutside });
40
+ if (!fs.existsSync(file)) return { ok: false, error: `no such file: ${target}` };
41
+ const stat = fs.statSync(file);
42
+ if (stat.isDirectory()) return { ok: false, error: `${target} is a directory` };
43
+ const buf = fs.readFileSync(file);
44
+ const truncated = buf.length > maxBytes;
45
+ return { ok: true, path: target, bytes: stat.size, truncated, content: buf.slice(0, maxBytes).toString('utf8') };
46
+ }
47
+
48
+ export function writeFileTool({ cwd, path: target, content = '', allowOutside = false } = {}) {
49
+ const file = resolveInside(cwd, target, { allowOutside });
50
+ fs.mkdirSync(path.dirname(file), { recursive: true });
51
+ fs.writeFileSync(file, content, 'utf8');
52
+ return { ok: true, path: target, bytes: Buffer.byteLength(content, 'utf8') };
53
+ }
54
+
55
+ export function editFileTool({ cwd, path: target, oldString, newString = '', replaceAll = false, allowOutside = false } = {}) {
56
+ const file = resolveInside(cwd, target, { allowOutside });
57
+ if (!fs.existsSync(file)) return { ok: false, error: `no such file: ${target}` };
58
+ if (typeof oldString !== 'string' || oldString.length === 0) return { ok: false, error: 'oldString is required and must be non-empty' };
59
+ const before = fs.readFileSync(file, 'utf8');
60
+ const occurrences = before.split(oldString).length - 1;
61
+ if (occurrences === 0) return { ok: false, error: 'oldString not found in file' };
62
+ if (occurrences > 1 && !replaceAll) return { ok: false, error: `oldString is not unique (${occurrences} matches); pass replaceAll or add more context` };
63
+ const after = replaceAll ? before.split(oldString).join(newString) : before.replace(oldString, newString);
64
+ fs.writeFileSync(file, after, 'utf8');
65
+ return { ok: true, path: target, replacements: replaceAll ? occurrences : 1 };
66
+ }
67
+
68
+ // Bounded depth-first walk yielding workspace-relative file paths, skipping the
69
+ // ignored dirs. Caps the number of files visited so a pathological tree cannot
70
+ // stall the loop.
71
+
72
+ function* walkFiles(root) {
73
+ const stack = [root];
74
+ let visited = 0;
75
+ while (stack.length) {
76
+ const dir = stack.pop();
77
+ let entries;
78
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { continue; }
79
+ for (const entry of entries) {
80
+ const full = path.join(dir, entry.name);
81
+ if (entry.isDirectory()) {
82
+ if (IGNORED_DIRS.has(entry.name) || entry.name.startsWith('.')) continue;
83
+ stack.push(full);
84
+ } else if (entry.isFile()) {
85
+ if (++visited > MAX_WALK_FILES) return;
86
+ yield full;
87
+ }
88
+ }
89
+ }
90
+ }
91
+
92
+ // Translate a simple glob ("**/*.mjs", "src/*.ts", "lib/**") into a RegExp. Only
93
+ // the common operators are supported (no brace expansion), which covers what the
94
+ // loop needs without pulling a glob dependency.
95
+
96
+ function globToRegExp(pattern) {
97
+ let re = '';
98
+ for (let i = 0; i < pattern.length; i++) {
99
+ const c = pattern[i];
100
+ if (c === '*') {
101
+ if (pattern[i + 1] === '*') { re += '.*'; i++; if (pattern[i + 1] === '/') i++; }
102
+ else re += '[^/]*';
103
+ } else if (c === '?') re += '[^/]';
104
+ else if ('.+^${}()|[]\\'.includes(c)) re += `\\${c}`;
105
+ else re += c;
106
+ }
107
+ return new RegExp(`^${re}$`);
108
+ }
109
+
110
+ export function globTool({ cwd, pattern, limit = 200, allowOutside = false } = {}) {
111
+ const root = resolveInside(cwd, '.', { allowOutside });
112
+ if (!pattern) return { ok: false, error: 'pattern is required' };
113
+ const rx = globToRegExp(pattern);
114
+ const matches = [];
115
+ for (const file of walkFiles(root)) {
116
+ const rel = path.relative(root, file);
117
+ if (rx.test(rel)) {
118
+ matches.push(rel);
119
+ if (matches.length >= limit) break;
120
+ }
121
+ }
122
+ return { ok: true, pattern, matches, truncated: matches.length >= limit };
123
+ }
124
+
125
+ export function grepTool({ cwd, pattern, glob = null, limit = 200, caseInsensitive = false, allowOutside = false } = {}) {
126
+ const root = resolveInside(cwd, '.', { allowOutside });
127
+ if (!pattern) return { ok: false, error: 'pattern is required' };
128
+ let rx;
129
+ try { rx = new RegExp(pattern, caseInsensitive ? 'i' : ''); } catch (err) { return { ok: false, error: `invalid pattern: ${err.message}` }; }
130
+ const globRx = glob ? globToRegExp(glob) : null;
131
+ const matches = [];
132
+ for (const file of walkFiles(root)) {
133
+ const rel = path.relative(root, file);
134
+ if (globRx && !globRx.test(rel)) continue;
135
+ let text;
136
+ try {
137
+ const stat = fs.statSync(file);
138
+ if (stat.size > MAX_READ_BYTES) continue;
139
+ text = fs.readFileSync(file, 'utf8');
140
+ } catch { continue; }
141
+ if (text.includes('\u0000')) continue;
142
+ const lines = text.split('\n');
143
+ for (let i = 0; i < lines.length; i++) {
144
+ if (rx.test(lines[i])) {
145
+ matches.push({ file: rel, line: i + 1, text: lines[i].slice(0, 300) });
146
+ if (matches.length >= limit) return { ok: true, pattern, matches, truncated: true };
147
+ }
148
+ }
149
+ }
150
+ return { ok: true, pattern, matches, truncated: false };
151
+ }
152
+
153
+ export async function shellTool({ cwd, command, timeoutSeconds = 60, allowOutside = false } = {}) {
154
+ if (!command || typeof command !== 'string') return { ok: false, error: 'command is required' };
155
+ const root = path.resolve(cwd);
156
+ const result = await runJob({
157
+ rootDir: root,
158
+ job: {
159
+ jobId: `chat-${randomUUID()}`,
160
+ command,
161
+ timeoutSeconds,
162
+ workspaceRef: root,
163
+ allowedPaths: allowOutside ? [] : [root],
164
+ },
165
+ });
166
+ let stdout = '';
167
+ let stderr = '';
168
+ try { stdout = fs.readFileSync(result.stdoutPath, 'utf8'); } catch { /* no stdout */ }
169
+ try { stderr = fs.readFileSync(result.stderrPath, 'utf8'); } catch { /* no stderr */ }
170
+ return {
171
+ ok: result.status === 'passed',
172
+ status: result.status,
173
+ exitCode: result.exitCode,
174
+ durationMs: result.durationMs,
175
+ stdout: stdout.slice(0, MAX_READ_BYTES),
176
+ stderr: stderr.slice(0, MAX_READ_BYTES),
177
+ };
178
+ }
179
+
180
+ export const __test__ = { resolveInside, globToRegExp };
@@ -0,0 +1,122 @@
1
+ /**
2
+ * apps/chat/engine/tools/registry.mjs — builds the owned loop's tool set as Vercel
3
+ * AI SDK tools, gated by the permission/sandbox policy.
4
+ *
5
+ * Each tool wraps a zero-dep primitive (primitives.mjs) behind the permission gate
6
+ * (permission.mjs): the gate runs first, and a denial returns a structured result
7
+ * the model can read rather than throwing, so the loop degrades gracefully instead
8
+ * of crashing on a blocked action. A single `construct_tool` bridges the loop to
9
+ * Construct's existing MCP tool surface via dispatchToolByName (mirroring the MCP
10
+ * `construct_call` meta-tool), so the loop reaches knowledge search, skills, and
11
+ * orchestration policy without re-declaring 60+ schemas here.
12
+ *
13
+ * `ai` and `zod` are imported lazily and only here, so the rest of the engine and
14
+ * all of its tests stay free of the optional dependencies.
15
+ */
16
+
17
+ import {
18
+ readFileTool, writeFileTool, editFileTool, globTool, grepTool, shellTool,
19
+ } from './primitives.mjs';
20
+ import { createPermissionGate } from './permission.mjs';
21
+
22
+ function denied(reason) {
23
+ return { ok: false, denied: true, error: reason };
24
+ }
25
+
26
+ export async function buildAgentTools({ env = process.env, cwd = process.cwd(), handlers = {}, only = null } = {}) {
27
+ const { tool } = await import('ai');
28
+ const { z } = await import('zod');
29
+
30
+ const gate = createPermissionGate({
31
+ getSandbox: handlers.getSandbox || (() => null),
32
+ getPermissionMode: handlers.getPermissionMode || (() => 'allow_once'),
33
+ requestPermission: handlers.requestPermission || null,
34
+ });
35
+
36
+ const defs = {
37
+ read: tool({
38
+ description: 'Read a UTF-8 text file from the workspace.',
39
+ inputSchema: z.object({ path: z.string().describe('workspace-relative file path') }),
40
+ execute: async ({ path: p }) => {
41
+ const verdict = await gate.check('read', { path: p });
42
+ if (!verdict.allowed) return denied(verdict.reason);
43
+ return readFileTool({ cwd, path: p, allowOutside: verdict.allowOutside });
44
+ },
45
+ }),
46
+ glob: tool({
47
+ description: 'Find files by glob pattern (supports * ** ?).',
48
+ inputSchema: z.object({ pattern: z.string(), limit: z.number().int().positive().max(1000).optional() }),
49
+ execute: async ({ pattern, limit }) => {
50
+ const verdict = await gate.check('glob', { pattern });
51
+ if (!verdict.allowed) return denied(verdict.reason);
52
+ return globTool({ cwd, pattern, limit, allowOutside: verdict.allowOutside });
53
+ },
54
+ }),
55
+ grep: tool({
56
+ description: 'Search file contents by regular expression, optionally filtered by a glob.',
57
+ inputSchema: z.object({
58
+ pattern: z.string(),
59
+ glob: z.string().optional(),
60
+ caseInsensitive: z.boolean().optional(),
61
+ limit: z.number().int().positive().max(1000).optional(),
62
+ }),
63
+ execute: async ({ pattern, glob, caseInsensitive, limit }) => {
64
+ const verdict = await gate.check('grep', { pattern });
65
+ if (!verdict.allowed) return denied(verdict.reason);
66
+ return grepTool({ cwd, pattern, glob, caseInsensitive, limit, allowOutside: verdict.allowOutside });
67
+ },
68
+ }),
69
+ write: tool({
70
+ description: 'Create or overwrite a workspace file with the given content.',
71
+ inputSchema: z.object({ path: z.string(), content: z.string() }),
72
+ execute: async ({ path: p, content }) => {
73
+ const verdict = await gate.check('write', { path: p });
74
+ if (!verdict.allowed) return denied(verdict.reason);
75
+ return writeFileTool({ cwd, path: p, content, allowOutside: verdict.allowOutside });
76
+ },
77
+ }),
78
+ edit: tool({
79
+ description: 'Replace an exact string in a workspace file. oldString must be unique unless replaceAll is set.',
80
+ inputSchema: z.object({
81
+ path: z.string(),
82
+ oldString: z.string(),
83
+ newString: z.string(),
84
+ replaceAll: z.boolean().optional(),
85
+ }),
86
+ execute: async ({ path: p, oldString, newString, replaceAll }) => {
87
+ const verdict = await gate.check('edit', { path: p });
88
+ if (!verdict.allowed) return denied(verdict.reason);
89
+ return editFileTool({ cwd, path: p, oldString, newString, replaceAll, allowOutside: verdict.allowOutside });
90
+ },
91
+ }),
92
+ shell: tool({
93
+ description: 'Run a bounded shell command in the workspace with a timeout.',
94
+ inputSchema: z.object({ command: z.string(), timeoutSeconds: z.number().int().positive().max(600).optional() }),
95
+ execute: async ({ command, timeoutSeconds }) => {
96
+ const verdict = await gate.check('shell', { command });
97
+ if (!verdict.allowed) return denied(verdict.reason);
98
+ return shellTool({ cwd, command, timeoutSeconds, allowOutside: verdict.allowOutside });
99
+ },
100
+ }),
101
+ construct_tool: tool({
102
+ description: 'Call a Construct MCP tool by name (e.g. knowledge_search, search_skills, orchestration_policy). Returns the tool result.',
103
+ inputSchema: z.object({ name: z.string(), args: z.record(z.string(), z.any()).optional() }),
104
+ execute: async ({ name, args }) => {
105
+ try {
106
+ const { dispatchToolByName } = await import('../../../../lib/mcp/server.mjs');
107
+ const result = await dispatchToolByName(name, args || {});
108
+ return { ok: true, name, result };
109
+ } catch (err) {
110
+ return { ok: false, name, error: err?.message || String(err) };
111
+ }
112
+ },
113
+ }),
114
+ };
115
+
116
+ if (!Array.isArray(only) || only.length === 0) return defs;
117
+ const filtered = {};
118
+ for (const name of only) if (defs[name]) filtered[name] = defs[name];
119
+ return filtered;
120
+ }
121
+
122
+ export const AGENT_TOOL_NAMES = ['read', 'glob', 'grep', 'write', 'edit', 'shell', 'construct_tool'];
@@ -0,0 +1,70 @@
1
+ /**
2
+ * apps/chat/engine/turn-controls.mjs — resolve one turn's execution controls from
3
+ * the compiled execution policy (construct-rv2x).
4
+ *
5
+ * The owned-loop engine (ai-sdk-agent.mjs) calls this once per turn to turn a
6
+ * capability profile plus the turn overlay into the concrete knobs streamText
7
+ * needs: the step cap, the output-token cap, caching eligibility, and the tool-
8
+ * group / schema budget, plus the continuation/compaction budget the session uses
9
+ * to decide when to compact context (construct-6zga.1.9). The capability profile
10
+ * is resolved from the active model id, so a mid-session model switch re-derives
11
+ * the envelope.
12
+ *
13
+ * Behavior preservation is the contract: this never throws and never returns a
14
+ * tighter envelope than today for a hosted-direct model. hosted-direct keeps the
15
+ * legacy step cap, the full tool set, and unbounded output; every other class
16
+ * enforces its compiled budget. An explicit CX_CHAT_MAX_STEPS operator override
17
+ * wins over the policy's step cap. Any failure in policy resolution falls back to
18
+ * the legacy envelope (16 steps, full tool set, no cap, no caching) so a policy
19
+ * bug can never break a chat turn.
20
+ */
21
+
22
+ import { resolveExecutionCapabilityProfile } from '../../../lib/models/execution-capability-profile.mjs';
23
+ import { compilePolicyFromOverlay } from '../../../lib/models/execution-policy.mjs';
24
+ import { continuationBudgetFromPolicy } from '../../../lib/chat/context-continuation.mjs';
25
+
26
+ const LEGACY_STEP_CAP = 16;
27
+
28
+ const LEGACY_CONTROLS = Object.freeze({
29
+ policy: null,
30
+ iterations: LEGACY_STEP_CAP,
31
+ outputCap: null,
32
+ cacheEligible: false,
33
+ allowedToolGroups: null,
34
+ maxToolSchemas: Infinity,
35
+ degraded: false,
36
+ continuation: Object.freeze({ triggerTokens: null, triggerRatio: null }),
37
+ });
38
+
39
+ function legacyControls() {
40
+ return { ...LEGACY_CONTROLS };
41
+ }
42
+
43
+ export function resolveTurnControls({ model = null, turnOverlay = null, env = {} } = {}) {
44
+ try {
45
+ const profile = resolveExecutionCapabilityProfile({ model });
46
+ const toolFailure = turnOverlay?.toolFailure === true;
47
+ const policy = compilePolicyFromOverlay({ profile, overlay: turnOverlay, toolFailure });
48
+
49
+ const envSteps = Number(env?.CX_CHAT_MAX_STEPS);
50
+ const iterations = envSteps > 0 ? Math.floor(envSteps) : policy.tools.maxToolIterations;
51
+
52
+ // hosted-direct is the mandated default path: keep today's unbounded output
53
+ // until live-probe evidence supersedes the compatibility_fallback tier. Every
54
+ // other class enforces its compiled output budget.
55
+ const outputCap = policy.source.capabilityClass === 'hosted-direct' ? null : policy.output.outputTokenBudget;
56
+
57
+ return {
58
+ policy,
59
+ iterations,
60
+ outputCap,
61
+ cacheEligible: policy.caching.eligible === true,
62
+ allowedToolGroups: policy.tools.allowedToolGroups,
63
+ maxToolSchemas: policy.tools.maxToolSchemas,
64
+ degraded: policy.degradedMode === true,
65
+ continuation: continuationBudgetFromPolicy(policy),
66
+ };
67
+ } catch {
68
+ return legacyControls();
69
+ }
70
+ }