@jc_stack/ez-agents 0.1.0-beta.33 → 0.1.0-beta.36

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 (157) hide show
  1. package/.dockerignore +1 -0
  2. package/.env.example +9 -16
  3. package/AGENTS.md +17 -9
  4. package/CHANGELOG.md +92 -0
  5. package/Dockerfile +11 -9
  6. package/README.md +32 -27
  7. package/THIRD_PARTY_NOTICES.md +4 -4
  8. package/bin/ez +97 -0
  9. package/bin/ezenciel-agents-plugin-broker.mjs +16 -0
  10. package/bin/ezenciel-agents-provision-telegram.mjs +13 -0
  11. package/bin/ezenciel-agents.mjs +1 -1
  12. package/compose.yaml +42 -5
  13. package/docker/entrypoint.sh +1 -1
  14. package/docker/healthcheck.mjs +12 -4
  15. package/docker/run.ts +5 -6
  16. package/docker/smoke.mjs +32 -7
  17. package/docs/application-channel.md +38 -10
  18. package/docs/architecture/ai-selection.md +3 -1
  19. package/docs/architecture/authority-boundaries.md +2 -2
  20. package/docs/channel-backend.md +4 -3
  21. package/docs/docker-runtime.md +106 -21
  22. package/docs/host-service.md +17 -6
  23. package/docs/local-qa.md +2 -2
  24. package/docs/plugin-guide.md +202 -0
  25. package/docs/plugins.md +63 -2
  26. package/docs/releasing.md +13 -0
  27. package/docs/repair.md +1 -1
  28. package/docs/responsive-channels.md +1 -1
  29. package/docs/scheduling.md +4 -4
  30. package/docs/setup.md +96 -16
  31. package/docs/standalone-cli.md +6 -5
  32. package/docs/upgrades.md +46 -23
  33. package/package.json +5 -5
  34. package/scripts/smoke-scheduler.ts +12 -4
  35. package/scripts/smoke.ts +14 -11
  36. package/src/agent-guidance.ts +6 -9
  37. package/src/agent-install.ts +44 -9
  38. package/src/ai-cli.ts +9 -7
  39. package/src/ai.ts +7 -7
  40. package/src/application-channel.ts +88 -17
  41. package/src/application-cli.ts +2 -2
  42. package/src/approval-cli.ts +14 -7
  43. package/src/approval.ts +27 -37
  44. package/src/channel-backend.ts +2 -3
  45. package/src/codex-session.ts +5 -3
  46. package/src/config.ts +18 -28
  47. package/src/control-state.ts +187 -9
  48. package/src/conversation-menu.ts +6 -17
  49. package/src/delivery-socket-client.d.mts +4 -0
  50. package/src/delivery-socket-client.mjs +104 -0
  51. package/src/delivery-socket.ts +354 -0
  52. package/src/execution-authority.ts +21 -5
  53. package/src/executor.ts +110 -31
  54. package/src/files.ts +38 -11
  55. package/src/host-executor.ts +50 -17
  56. package/src/inbox.ts +15 -49
  57. package/src/index.ts +96 -52
  58. package/src/install-config.ts +2 -2
  59. package/src/install-tools.mjs +100 -23
  60. package/src/isolation.ts +25 -0
  61. package/src/ledger-endpoint.d.mts +2 -0
  62. package/src/ledger-endpoint.mjs +17 -0
  63. package/src/menu.ts +16 -8
  64. package/src/message-history.ts +13 -18
  65. package/src/message.ts +35 -18
  66. package/src/plugin-broker.mjs +396 -0
  67. package/src/plugins/connection.mjs +2 -2
  68. package/src/plugins/manager.mjs +178 -26
  69. package/src/plugins/native-tasks.mjs +2 -2
  70. package/src/prompt-suffix.ts +12 -0
  71. package/src/react.ts +6 -4
  72. package/src/runs.ts +156 -243
  73. package/src/schedule-cli.ts +29 -10
  74. package/src/scheduled-tasks.ts +53 -10
  75. package/src/scheduler.ts +20 -7
  76. package/src/service.ts +3 -3
  77. package/src/setup.ts +11 -7
  78. package/src/software-status.ts +36 -4
  79. package/src/task-executor.ts +6 -3
  80. package/src/task-workspace.ts +4 -3
  81. package/src/tasks.ts +1 -1
  82. package/src/telegram-provisioning-cli.ts +22 -0
  83. package/src/telegram-provisioning.ts +214 -0
  84. package/src/updates/control.mjs +77 -7
  85. package/src/updates/runtime.mjs +29 -9
  86. package/src/updates/status.mjs +25 -3
  87. package/src/updates/supervisor.mjs +31 -18
  88. package/src/version.ts +20 -0
  89. package/src/workspace-confine.ts +38 -0
  90. package/src/workspace.ts +24 -20
  91. package/templates/agent-purpose.md +1 -0
  92. package/templates/failure-review.md +1 -1
  93. package/templates/maintainer-purpose.md +1 -1
  94. package/test/agent-guidance.test.ts +18 -88
  95. package/test/agent-install.test.ts +48 -0
  96. package/test/ai-cli.test.ts +18 -0
  97. package/test/ai.test.ts +84 -0
  98. package/test/application-channel.test.ts +66 -15
  99. package/test/application-controls.test.ts +56 -3
  100. package/test/application-only.test.ts +16 -13
  101. package/test/channel-backend.test.ts +3 -7
  102. package/test/channel-delivery.test.ts +4 -1
  103. package/test/channel-owner.test.ts +6 -3
  104. package/test/codex-context.test.ts +63 -3
  105. package/test/codex-session.test.ts +6 -1
  106. package/test/config.test.ts +47 -37
  107. package/test/control-state.test.ts +83 -4
  108. package/test/conversation-menu.test.ts +2 -4
  109. package/test/delivery-transport.test.ts +72 -0
  110. package/test/docker-runtime.test.ts +27 -14
  111. package/test/engine-handoff.test.ts +12 -8
  112. package/test/event-sources.test.ts +2 -2
  113. package/test/execution-authority.test.ts +9 -9
  114. package/test/executor.test.ts +47 -11
  115. package/test/failure.test.ts +18 -5
  116. package/test/files.test.ts +2 -2
  117. package/test/helpers/ledger.ts +18 -0
  118. package/test/host-executor.test.ts +80 -0
  119. package/test/inbox.test.ts +8 -10
  120. package/test/install-config.test.ts +18 -6
  121. package/test/install-tools.test.mjs +80 -7
  122. package/test/intake-relay.test.ts +58 -11
  123. package/test/message-history.test.ts +39 -47
  124. package/test/native-tasks.test.ts +1 -1
  125. package/test/plugin-broker.test.mjs +172 -0
  126. package/test/plugin-manager.test.mjs +143 -5
  127. package/test/reaction.test.ts +4 -0
  128. package/test/relay.test.ts +5 -7
  129. package/test/repair-policy.test.ts +1 -4
  130. package/test/schedule-cli.test.ts +14 -9
  131. package/test/scheduled-tasks.test.ts +29 -6
  132. package/test/scheduler-host.test.ts +5 -5
  133. package/test/scheduler-relay.test.ts +15 -9
  134. package/test/scheduler.test.ts +2 -2
  135. package/test/security.test.ts +6 -3
  136. package/test/software-status.test.ts +21 -3
  137. package/test/telegram-provisioning.test.ts +160 -0
  138. package/test/updates.test.mjs +102 -13
  139. package/test/workspace-confine.test.ts +47 -0
  140. package/test/workspace.test.ts +27 -11
  141. package/bin/ezenciel-agents-watch.mjs +0 -8
  142. package/compose.workforce-watch.yaml +0 -33
  143. package/docker/recovery.ts +0 -11
  144. package/docs/pagerduty.md +0 -42
  145. package/docs/workforce-watch.md +0 -101
  146. package/src/pagerduty.ts +0 -109
  147. package/src/reply-context.ts +0 -44
  148. package/src/update-attention.ts +0 -18
  149. package/src/workforce-watch-cli.ts +0 -14
  150. package/src/workforce-watch.ts +0 -155
  151. package/templates/agent/AGENTS.md +0 -15
  152. package/templates/agent/SOUL.md +0 -11
  153. package/templates/agent/USER.md +0 -5
  154. package/templates/agent-guidance.md +0 -114
  155. package/test/pagerduty.test.ts +0 -104
  156. package/test/update-attention.test.ts +0 -20
  157. package/test/workforce-watch.test.ts +0 -180
package/docs/upgrades.md CHANGED
@@ -16,9 +16,9 @@ The agent owns release review, policy decisions and communication. The host
16
16
  supervisor owns interruption-safe replacement. There is one host service per
17
17
  agent, not a second agent or an additional updater daemon. Its replaceable child
18
18
  runs the normal CLI transport. It checks npm every six hours while running and
19
- queues an owner-bound maintenance turn only when an automatic channel changes.
20
- No owner means no maintenance executor. Normal user work and maintenance share
21
- one serial queue. Checks use the installed scoped npm identity; failures are
19
+ records automatic-channel changes; discovery never wakes the agent or injects
20
+ wrapper state into a session. Updates stay owner-invoked through `ez updates`.
21
+ Checks use the installed scoped npm identity; failures are
22
22
  visible in `updates check` and private `tools/updates/available.json`. Plugins marked
23
23
  `private: true` in their package metadata are reported as local-source updates
24
24
  only, without querying public npm; this does not mean they are up to date.
@@ -144,7 +144,7 @@ rollback is a recovery operation for the previous installation only.
144
144
  queuing it.** It must not wait for completion in that same turn. The supervisor
145
145
  pauses new run admission, drains already-started work, then consumes the job.
146
146
  One job at a time; an unresolved recovery blocks new upgrades. The agent processes
147
- multiple requested packages over successive maintenance turns.
147
+ multiple requested packages over successive update requests.
148
148
 
149
149
  The exact archive is reverified and re-extracted before execution; editing a
150
150
  prepared tree cannot substitute code. Main dependencies install with the frozen
@@ -164,24 +164,43 @@ running. Failed activation restores the previous code/configuration and checks i
164
164
  If recovery itself fails, inspect and fix the reported infrastructure problem,
165
165
  then use `ez updates recover <job-id>` and finish the turn. This retries only the
166
166
  saved code/configuration recovery, not provider operations.
167
- Completion or failure wakes the agent to inspect the receipt and report naturally.
167
+ An update never wakes the agent or injects wrapper state into its session; the
168
+ owner or agent inspects receipts with `ez updates` when asked.
168
169
 
169
170
  Backups contain credentials and must stay private. Main backups cover the
170
171
  canonical mind/control and deployment files. Plugins back up existing named
171
172
  volumes while their services are stopped, using the previous image's `tar` and
172
173
  read-only volume mounts; archive output is written by the host with mode 0600.
173
- No backup deletes live data or revokes credentials. Retain old package roots and
174
- images until QA and any recovery window are complete; there is no automatic GC.
174
+ No backup deletes live data or revokes credentials. After a successful update, the
175
+ supervisor retains the newest completed backup per target and removes backup
176
+ directories from older terminal receipts (`completed`, `failed` or
177
+ `rolled-back`). Queued, applying and recovery-required jobs are never pruned. Old
178
+ package roots and images remain available until they are no longer needed for the
179
+ active or immediate rollback path; backup cleanup does not remove them. A cleanup
180
+ failure is recorded on the completed receipt and does not turn a successful
181
+ update into a rollback. The supervisor repeats this reconciliation at startup so
182
+ a release restart also cleans backups left by a crash window or by the release
183
+ that installed the policy.
175
184
 
176
185
  The updater accepts only matching state-schema and protocol contracts and an
177
- unchanged deployment layout. Plugins may add command routes to existing services;
178
- existing routes and all services, privileges, volumes and other deployment
179
- configuration must remain unchanged. Incompatible changes fail before replacement,
180
- even for an explicit candidate, and need a separately reviewed migration rather
181
- than an override flag. Release authors must truthfully declare schema compatibility.
182
- Code rollback **does not rewind private
183
- state**, provider cursors or operation receipts; uncertain actions are never
184
- replayed. Docker health is not proof of live provider identity or delivery.
186
+ unchanged effective deployment layout. The reviewed beta.34 runtime migration
187
+ allows the optional empty `EZ_ISOLATION` passthrough and a changed purpose-file
188
+ fallback when the deployment already binds `EZ_AGENT_PURPOSE_FILE`; the job
189
+ receipt records that migration. Plugins may add command routes to existing
190
+ services; existing routes and all services, privileges, volumes and other
191
+ deployment configuration must remain unchanged. Incompatible changes fail
192
+ before replacement, even for an explicit candidate, and need a separately
193
+ reviewed migration rather than an override flag. Release authors must truthfully
194
+ declare schema compatibility. Code rollback **does not rewind private state**,
195
+ provider cursors or operation receipts; uncertain actions are never replayed.
196
+ Docker health is not proof of live provider identity or delivery.
197
+
198
+ The updater also records the exact Library beta14 command migration: it removes
199
+ the retired `library-document` route and changes `library-query` from
200
+ `query-context` to `search`, while requiring every other manifest and deployment
201
+ field to remain unchanged. A completed main upgrade exits the active supervisor
202
+ after publishing its receipt; the retained bootstrap is then restarted by the
203
+ host service and loads the new package root.
185
204
 
186
205
  ## Contributor acceptance
187
206
 
@@ -214,12 +233,16 @@ policy selects non-deprecated stable versions, even when latest is a prerelease.
214
233
  No eligible version is reported as available:null with newer:false. Older installed
215
234
  updaters need an exact-version core update to adopt this discovery behavior.
216
235
 
217
- ## Shared agent guidance
236
+ ## Operating-agent instructions
218
237
 
219
- Setup and runtime startup install `templates/agent-guidance.md` into a marked
220
- section of the workspace's native `AGENTS.md` (and existing `AGENTS.override.md`).
221
- Upgrade refreshes only that section; personal content outside it is preserved
222
- byte-for-byte. New scheduled task workspaces receive the same shared guidance.
238
+ Setup and the main upgrade step strip any obsolete `<!-- ez shared guidance -->`
239
+ handbook from workspace `AGENTS.md` (and existing `AGENTS.override.md`).
240
+ Personal text outside that block is preserved byte-for-byte. Do not reinsert
241
+ coding, KISS, contribution or repair loops into operating minds.
242
+
243
+ The package-owned locator is the managed `<!-- ez tools -->` block: the bound
244
+ `ez` launcher, `ez --help`, and `ez tools list --details`. Inventory is
245
+ generated on read. Plugin registry init and update binding refresh that locator.
223
246
  Malformed markers and symlinks fail visibly rather than overwriting personal work.
224
247
 
225
248
  Codex, agy, Grok and OpenCode discover workspace instructions natively. Claude
@@ -236,9 +259,9 @@ preserved. Restricted contact tasks retain their separate
236
259
  bounded instruction scopes. For delivered busy replies absent from the native
237
260
  conversation, the owner engine can call `ezenciel-agents-schedule context`.
238
261
 
239
- Keep general defaults in the shipped shared file and identity/preferences in
240
- workspace personal files. Instructions cannot grant permissions; explicit owner
241
- requests take precedence within existing execution authority.
262
+ Keep identity and purpose in the agent's own `AGENTS.md`. Instructions cannot
263
+ grant permissions; explicit owner requests take precedence within existing
264
+ execution authority.
242
265
 
243
266
  Update discovery runs independently of active host work. A discovery failure is
244
267
  logged locally and retried at the next regular six-hour check; it does not stop
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jc_stack/ez-agents",
3
- "version": "0.1.0-beta.33",
3
+ "version": "0.1.0-beta.36",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "A lightweight foundation for persistent business AI assistants using existing AI harnesses, workspaces and plugins.",
@@ -21,8 +21,9 @@
21
21
  "ezenciel-agents-host": "bin/ezenciel-agents-host",
22
22
  "ezenciel-agents-tools": "bin/ezenciel-agents-tools.mjs",
23
23
  "ezenciel-agents-ai": "bin/ezenciel-agents-ai.mjs",
24
- "ezenciel-agents-watch": "bin/ezenciel-agents-watch.mjs",
25
- "ezenciel-agents-application": "bin/ezenciel-agents-application.mjs"
24
+ "ezenciel-agents-application": "bin/ezenciel-agents-application.mjs",
25
+ "ezenciel-agents-provision-telegram": "bin/ezenciel-agents-provision-telegram.mjs",
26
+ "ezenciel-agents-plugin-broker": "bin/ezenciel-agents-plugin-broker.mjs"
26
27
  },
27
28
  "files": [
28
29
  "default-plugins.json",
@@ -37,7 +38,6 @@
37
38
  "CONTRIBUTING.md",
38
39
  "Dockerfile",
39
40
  "compose.yaml",
40
- "compose.workforce-watch.yaml",
41
41
  "docker",
42
42
  "compose.whatsapp.yaml",
43
43
  "scripts/smoke.ts",
@@ -61,7 +61,7 @@
61
61
  "scripts": {
62
62
  "setup": "tsx --env-file-if-exists=.env src/setup.ts",
63
63
  "dev": "EZ_DEVELOPMENT=1 tsx watch --clear-screen=false --exclude 'agent/**' --exclude 'test/**' --env-file=.env src/index.ts",
64
- "start": "./bin/ezenciel-agents-docker up -d --wait relay",
64
+ "start": "./bin/ezenciel-agents-docker up -d --wait",
65
65
  "owner": "tsx --env-file=.env src/owner.ts",
66
66
  "message": "tsx src/message.ts",
67
67
  "react": "tsx src/react.ts",
@@ -7,6 +7,8 @@ import { createRelay } from '../src/index.js'
7
7
  import { ControlStore } from '../src/control-state.js'
8
8
  import { Scheduler } from '../src/scheduler.js'
9
9
  import { RunStore } from '../src/runs.js'
10
+ import { serveDeliverySocket, createLedgerHandler } from '../src/delivery-socket.js'
11
+ import { packageVersion } from '../src/version.js'
10
12
  import { initialPreset } from '../src/ai.js'
11
13
  import { initializeWorkspace } from '../src/workspace.js'
12
14
  import type { Update } from 'grammy/types'
@@ -15,12 +17,18 @@ const duration=Number(process.argv[2] || 1860),cli=process.argv[3] || 'codex'
15
17
  const nativeGoal=process.argv[4]==='goal'
16
18
  if(!Number.isSafeInteger(duration) || duration<30)throw new Error('Duration must be at least 30 seconds')
17
19
  const root=await mkdtemp(join(tmpdir(),'ez-scheduler-smoke-')),workspace=join(root,'agent'),controlDir=join(root,'control')
18
- await initializeWorkspace(workspace)
20
+ const purpose=join(root,'purpose.md');await writeFile(purpose,'Verify native scheduled work and responsive owner chat.\n')
21
+ await initializeWorkspace(workspace,purpose)
19
22
  const control=new ControlStore(controlDir,1000),scheduler=new Scheduler(controlDir),runs=new RunStore(controlDir)
20
23
  await control.requestPairing(101,101);await control.approveOwner(101)
21
24
  const owner=(await control.status()).owner!,execution=await control.captureChoice(initialPreset(cli))
22
25
  const replies:{at:number;text:string}[]=[]
23
26
  const relay=createRelay({workspace,controlDir,pairingTtlMs:1000,executorTimeoutMs:0,executorCli:cli,telegramBotToken:'fixture'})
27
+ // Engine children reach this process's memory ledger through the socket.
28
+ const ledger=await serveDeliverySocket(controlDir,createLedgerHandler(controlDir,{
29
+ wake:()=>{void relay.drainOutbox()},
30
+ status:()=>({polling:false,applicationOnly:!relay.telegramEnabled,telegramConfigured:true,version:packageVersion}),
31
+ }))
24
32
  relay.bot.botInfo={id:999,is_bot:true,first_name:'Fixture',username:'fixture_bot'} as typeof relay.bot.botInfo
25
33
  relay.bot.api.config.use(async(_previous,method,payload)=>{
26
34
  if(method==='sendMessage') {const reply={at:Date.now(),text:(payload as {text:string}).text};replies.push(reply);console.log(JSON.stringify({reply}))}
@@ -58,11 +66,11 @@ try{
58
66
  await relay.drainOutbox()
59
67
  const status=(await runs.get(background.id))?.status
60
68
  if(status!=='completed' || replies.filter(r=>r.text.includes('BACKGROUND_DONE')).length!==1)throw new Error('Missing completed run or exactly one delivered result')
61
- const finished=await readFile(join(workspace,'work/tasks',background.id,'finished.txt'),'utf8')
69
+ const finished=await readFile(join(controlDir,'work/tasks',background.id,'finished.txt'),'utf8')
62
70
  if(finished.trim()!=='DONE')throw new Error('Missing finished.txt artifact')
63
71
  if(nativeGoal){
64
72
  for(const [file,expected] of [['phase1.txt','ONE'],['phase2.txt','TWO']])
65
- if((await readFile(join(workspace,'work/tasks',background.id,file),'utf8')).trim()!==expected)throw new Error(`Missing native goal artifact: ${file}`)
73
+ if((await readFile(join(controlDir,'work/tasks',background.id,file),'utf8')).trim()!==expected)throw new Error(`Missing native goal artifact: ${file}`)
66
74
  }
67
75
  const record=(await runs.get(background.id))!
68
76
  if(Date.parse(record.endedAt!)-Date.parse(record.startedAt!) < duration*1000)throw new Error('Worker completed before requested duration')
@@ -87,4 +95,4 @@ try{
87
95
  const evidence={duration,cli,nativeGoal,goalEvidence,status,replies,run:await runs.get(background.id)}
88
96
  await writeFile(join(root,'evidence.json'),JSON.stringify(evidence,null,2),{mode:0o600})
89
97
  console.log(JSON.stringify({passed:true,evidence:join(root,'evidence.json')}))
90
- }finally{clearInterval(tick);while(draining)await new Promise(r=>setTimeout(r,50));await relay.stop()}
98
+ }finally{clearInterval(tick);while(draining)await new Promise(r=>setTimeout(r,50));await relay.stop();await ledger.stop()}
package/scripts/smoke.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  import { dirname, join } from 'node:path'
2
- import { readdir, readFile } from 'node:fs/promises'
3
2
  import { fileURLToPath } from 'node:url'
4
3
  import { randomUUID } from 'node:crypto'
5
4
  import { loadConfig } from '../src/config.js'
6
5
  import { ControlStore } from '../src/control-state.js'
7
6
  import { startExecutorJob, terminateJob } from '../src/executor.js'
8
- import { RunStore } from '../src/runs.js'
7
+ import { RunStore, sentOutbox } from '../src/runs.js'
9
8
  import { createRelay } from '../src/index.js'
9
+ import { serveDeliverySocket, createLedgerHandler } from '../src/delivery-socket.js'
10
+ import { packageVersion } from '../src/version.js'
10
11
 
11
12
  // Outbound integration test, not proof of Telegram intake or UI interactions.
12
13
  // Run while the polling relay is stopped; the owner must already be paired.
@@ -39,6 +40,11 @@ async function main() {
39
40
  texts: [prompt],
40
41
  })
41
42
  await runs.patch(run.id, { status: 'running', startedAt: new Date().toISOString() })
43
+ // The engine child reaches the smoke-process memory ledger through the socket.
44
+ const ledger = await serveDeliverySocket(config.controlDir, createLedgerHandler(config.controlDir, {
45
+ wake: () => { void relay.drainOutbox(run.id) },
46
+ status: () => ({ polling: false, applicationOnly: !relay.telegramEnabled, telegramConfigured: config.telegramBotToken !== '', version: packageVersion }),
47
+ }))
42
48
  const job = await startExecutorJob(run.texts, {
43
49
  workspace: config.workspace,
44
50
  timeoutMs: config.executorTimeoutMs,
@@ -72,18 +78,14 @@ async function main() {
72
78
  status: code === 0 ? 'completed' : 'failed',
73
79
  endedAt: new Date().toISOString(),
74
80
  })
75
- const names = (await readdir(join(config.controlDir, 'outbox'))).filter((name) =>
76
- name.startsWith(run.id + '_'),
77
- )
78
- const receipts = []
79
- for (const name of names.filter((name) => name.endsWith('.sent.json'))) {
80
- const item = JSON.parse(await readFile(join(config.controlDir, 'outbox', name), 'utf8'))
81
- if (item.receipt) receipts.push(item.receipt)
82
- }
81
+ const receipts = sentOutbox(config.controlDir)
82
+ .filter((item) => item.runId === run.id && item.receipt)
83
+ .map((item) => item.receipt)
84
+ const delivery = await runs.deliveryStatus()
83
85
  console.log(
84
86
  JSON.stringify({ runId: run.id, executor: config.executorCli, model: choice?.model, effort: choice?.effort, exitCode: code, receipts }, null, 2),
85
87
  )
86
- if (code !== 0 || !receipts.length || names.some((name) => !name.endsWith('.sent.json'))) {
88
+ if (code !== 0 || !receipts.length || (await runs.pendingOutbox()).length || delivery.failed || delivery.unknown) {
87
89
  throw new Error('Smoke failed: executor failure, missing receipt, or undelivered outbox item')
88
90
  }
89
91
  console.log('Outbound smoke passed. Telegram intake and button/media UI still require a live chat test.')
@@ -93,6 +95,7 @@ async function main() {
93
95
  process.removeListener('SIGTERM', stop)
94
96
  await job.cleanup()
95
97
  await relay.stop()
98
+ await ledger.stop()
96
99
  }
97
100
  }
98
101
 
@@ -1,17 +1,12 @@
1
1
  import { lstat, readFile, rename, rm, writeFile } from 'node:fs/promises'
2
2
  import { randomUUID } from 'node:crypto'
3
3
  import path from 'node:path'
4
- import { readFileSync } from 'node:fs'
5
-
6
- // Resolve against the installed package, never the agent's editable workspace.
7
- export const agentGuidance = (): string =>
8
- readFileSync(new URL('../templates/agent-guidance.md', import.meta.url), 'utf8').trim()
9
4
 
10
5
  const start = '<!-- ez shared guidance: begin -->'
11
6
  const end = '<!-- ez shared guidance: end -->'
12
7
 
13
- // Native instruction installation, refreshed at setup/runtime upgrade, not per turn.
14
- // Personal instructions outside this one managed block remain byte-for-byte intact.
8
+ // Drop the obsolete package-owned handbook. Discovery lives in the managed
9
+ // ez tools locator. Personal text outside the markers stays byte-for-byte.
15
10
  export async function installAgentGuidance(workspace: string): Promise<void> {
16
11
  for (const name of ['AGENTS.md', 'AGENTS.override.md']) {
17
12
  const file = path.join(workspace, name)
@@ -23,11 +18,13 @@ export async function installAgentGuidance(workspace: string): Promise<void> {
23
18
  if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue
24
19
  throw error
25
20
  }
26
- const block = `${start}\n${agentGuidance()}\n${end}\n\n`
27
21
  const from = original.indexOf(start), to = original.indexOf(end)
28
22
  if ((from < 0) !== (to < 0) || (from >= 0 && (to < from || original.indexOf(start, from + start.length) >= 0 || original.indexOf(end, to + end.length) >= 0)))
29
23
  throw new Error(`Malformed shared guidance block: ${file}`)
30
- const updated = from < 0 ? block + original : original.slice(0, from) + block.trimEnd() + original.slice(to + end.length)
24
+ if (from < 0) continue
25
+ let rest = original.slice(to + end.length)
26
+ if (from === 0 && rest.startsWith('\n')) rest = rest.slice(1)
27
+ const updated = original.slice(0, from) + rest
31
28
  if (updated === original) continue
32
29
  const temporary = `${file}.${randomUUID()}.tmp`
33
30
  try {
@@ -1,8 +1,13 @@
1
- import { mkdir, readFile, writeFile, rm, readdir } from 'node:fs/promises'
2
- import { isAbsolute, join, resolve, dirname } from 'node:path'
1
+ import { chmod, mkdir, readFile, writeFile, rm, readdir } from 'node:fs/promises'
2
+ import { createHash } from 'node:crypto'
3
+ import { isAbsolute, join, resolve, dirname, delimiter } from 'node:path'
3
4
  import { parseArgs } from 'node:util'
4
5
  import { executorKey } from './executor.js'
6
+ import { isolationTransport, parseIsolationClass, type IsolationClass } from './isolation.js'
7
+ import { ledgerOverlayName, ledgerOverlayYaml } from './ledger-endpoint.mjs'
8
+ import { initializeWorkspace } from './workspace.js'
5
9
  import { fileURLToPath } from 'node:url'
10
+ import { validateCodexProvider, type CodexProviderBinding } from './executor.js'
6
11
 
7
12
  // Recorded by the installing CLI once; agent creation inherits this binding.
8
13
  export const installationCli = async (root: string, installerCli?: string): Promise<string> => {
@@ -30,42 +35,70 @@ export const installationCli = async (root: string, installerCli?: string): Prom
30
35
  }
31
36
 
32
37
  export const createAgent = async (options: {
33
- root: string; hostRoot: string; composeFile: string; name: string; purpose: string; token: string; cli?: string; image?: string
38
+ root: string; hostRoot: string; composeFile: string; name: string; purpose: string; token: string; cli?: string; image?: string; isolation?: string; codexProvider?: CodexProviderBinding; ledgerPort?: number
34
39
  }) => {
35
40
  const { root, hostRoot, composeFile, name, purpose, token } = options
41
+ const requestedIsolation = options.isolation?.trim()
42
+ if (requestedIsolation) parseIsolationClass(requestedIsolation)
36
43
  if (!/^[a-z][a-z0-9-]{0,39}$/.test(name)) throw new Error('Use an agent name of 1–40 lowercase letters, digits or hyphens, starting with a letter.')
37
44
  if (![root, hostRoot, composeFile].every(p => isAbsolute(p) && !/[\r\n\0']/.test(p)))
38
45
  throw new Error('Installation paths must be absolute and contain no newline or single quote.')
39
- if (!purpose.trim() || purpose.length > 12000) throw new Error('Supply a purpose of 1–12000 characters.')
46
+ if (!purpose.trim() || purpose.length > 2000) throw new Error('Supply a concise purpose of 1–2000 characters.')
40
47
  if (!/^\d{5,}:[A-Za-z0-9_-]{20,}$/.test(token)) throw new Error('Supply the BotFather token through stdin.')
41
48
  const image=options.image||'ezenciel-agents:local'
42
49
  if(!/^[a-zA-Z0-9][a-zA-Z0-9._/:@-]{0,255}$/.test(image))throw new Error('Invalid relay image reference')
43
50
  await mkdir(root, {recursive:true, mode:0o700})
44
51
  const cli = await installationCli(root, options.cli)
52
+ const isolation: IsolationClass = requestedIsolation ? parseIsolationClass(requestedIsolation) : cli === 'codex' ? 'isolated' : 'host-capable'
53
+ if (isolation === 'isolated' && cli !== 'codex') throw new Error(`Isolated execution is unavailable for ${cli}; use host-capable isolation`)
54
+ const transport = isolationTransport(isolation)
55
+ const ledgerPort = isolation === 'host-capable'
56
+ ? options.ledgerPort ?? 20000 + (createHash('sha256').update(name).digest().readUInt16BE(0) % 10000)
57
+ : undefined
58
+ if (isolation === 'host-capable' && (!Number.isSafeInteger(ledgerPort) || ledgerPort! < 1024 || ledgerPort! > 65535))
59
+ throw new Error('Host-capable agents require a free loopback ledger port for host CLI access')
60
+ const codexProvider = options.codexProvider ? validateCodexProvider(options.codexProvider) : undefined
61
+ if (codexProvider && cli !== 'codex') throw new Error('A Codex provider requires the Codex installation CLI')
45
62
  const directory = join(root, name), deploymentDir = join(hostRoot, name)
46
63
  // Exclusive directory creation: a repeated name never overwrites another agent.
47
64
  await mkdir(directory, {mode:0o700})
48
65
  try {
49
66
  const project = `ez-agent-${name}`
67
+ const ledgerOverlay = join(deploymentDir, ledgerOverlayName)
50
68
  const values = {
51
69
  COMPOSE_PROJECT_NAME: project,
52
- COMPOSE_FILE: composeFile,
70
+ COMPOSE_FILE: [composeFile, ...(ledgerPort ? [ledgerOverlay] : [])].join(delimiter),
53
71
  EZ_RELAY_IMAGE: image,
54
72
  EZ_RELAY_ENV_FILE: join(deploymentDir, 'relay.env'),
55
73
  EZ_AGENT_PURPOSE_FILE: join(deploymentDir, 'purpose.md'),
56
74
  EZ_EXECUTOR_CLI: cli,
75
+ EZ_ISOLATION: isolation,
76
+ EZ_EXECUTOR_TRANSPORT: transport,
77
+ ...(ledgerPort ? { EZ_DELIVERY_TCP_PORT: String(ledgerPort) } : {}),
78
+ ...(isolation === 'isolated' && cli === 'codex' ? { EZ_CODEX_SANDBOX: 'external' } : {}),
57
79
  EZ_AGENT_WORKSPACE: join(deploymentDir, 'mind'),
58
80
  EZ_CONTROL_DIR: join(deploymentDir, 'control'),
81
+ EZ_TOOLS_HOME: join(deploymentDir, 'tools'),
82
+ EZ_PLUGIN_BROKER_SOCKET: join(deploymentDir, 'control', 'plugin-broker.sock'),
83
+ EZ_PLUGIN_BROKER_HOST_CONFIG: join(deploymentDir, 'host-executor.json'),
84
+ ...(isolation === 'isolated' ? { COMPOSE_PROFILES: 'isolated' } : {}),
59
85
  EZ_WHATSAPP_IPC_VOLUME: `${project}-whatsapp-ipc`,
60
86
  EZ_WHATSAPP_CLIENT_VOLUME: `${project}-whatsapp-client`,
61
87
  }
62
88
  await writeFile(join(directory, 'docker.env'), Object.entries(values).map(([k,v]) => `${k}='${v}'\n`).join(''), {mode:0o600, flag:'wx'})
89
+ if (ledgerPort) await writeFile(join(directory, ledgerOverlayName), ledgerOverlayYaml(), {mode:0o600, flag:'wx'})
63
90
  await writeFile(join(directory, 'relay.env'), `TELEGRAM_BOT_TOKEN=${token}\n`, {mode:0o600, flag:'wx'})
64
91
  await writeFile(join(directory, 'purpose.md'), purpose.trim()+'\n', {mode:0o644, flag:'wx'})
65
92
  await mkdir(join(directory,'mind'),{mode:0o700})
93
+ // Install-time seed: the relay never writes the workspace at startup.
94
+ // Readable beyond the installer UID so a mismatched runtime UID still
95
+ // loads its own purpose; the 0700 deployment directory keeps it private.
96
+ const seeded = await initializeWorkspace(join(directory,'mind'), join(directory,'purpose.md'))
97
+ if (seeded.includes('AGENTS.md')) await chmod(join(directory,'mind','AGENTS.md'), 0o644)
66
98
  await mkdir(join(directory,'control'),{mode:0o700})
67
- const agent = {name, project, deploymentDir, purpose:purpose.trim(), executor:cli}
68
- const host = {cli,agents:[{name,workspace:join(deploymentDir,'mind'),controlDir:join(deploymentDir,'control'),binDir:join(dirname(composeFile),'bin')}]}
99
+ await mkdir(join(directory,'tools'),{mode:0o700})
100
+ const agent = {name, project, deploymentDir, purpose:purpose.trim(), executor:cli, isolation}
101
+ const host = {cli,isolation,agents:[{name,workspace:join(deploymentDir,'mind'),controlDir:join(deploymentDir,'control'),binDir:join(dirname(composeFile),'bin'),...(isolation === 'isolated' ? {toolsHome:join(deploymentDir,'tools')} : {}),...(codexProvider?{codexProviders:[codexProvider]}:{})}]}
69
102
  await writeFile(join(directory,'host-executor.json'),JSON.stringify(host,null,2)+'\n',{mode:0o600,flag:'wx'})
70
103
  await writeFile(join(directory, 'agent.json'), JSON.stringify(agent,null,2)+'\n', {mode:0o600, flag:'wx'})
71
104
  return agent
@@ -84,13 +117,15 @@ export const listAgents = async (root: string) => {
84
117
 
85
118
  if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
86
119
  try {
87
- const {values:v} = parseArgs({options:{name:{type:'string'},purpose:{type:'string'},'host-root':{type:'string'},'compose-file':{type:'string'},'relay-image':{type:'string'},list:{type:'boolean'},cli:{type:'string'},'register-cli':{type:'string'}}})
120
+ const {values:v} = parseArgs({options:{name:{type:'string'},purpose:{type:'string'},isolation:{type:'string'},'host-root':{type:'string'},'compose-file':{type:'string'},'relay-image':{type:'string'},'ledger-port':{type:'string'},list:{type:'boolean'},cli:{type:'string'},'register-cli':{type:'string'},'codex-provider':{type:'string'},'codex-provider-name':{type:'string'},'codex-base-url':{type:'string'},'codex-env-key':{type:'string'},'codex-model':{type:'string',multiple:true}}})
88
121
  if (v['register-cli']) console.log(JSON.stringify({cli:await installationCli('/installations',v['register-cli'])}))
89
122
  else if (v.list) console.log(JSON.stringify(await listAgents('/installations')))
90
123
  else {
91
124
  let token=''
92
125
  for await (const chunk of process.stdin) { token+=chunk; if(token.length>512) throw new Error('Token input is too long.') }
93
- console.log(JSON.stringify(await createAgent({root:'/installations',hostRoot:v['host-root']||'',composeFile:v['compose-file']||'',name:v.name||'',purpose:v.purpose||'',token:token.trim(),cli:v.cli||'',image:v['relay-image']})))
126
+ const providerValues=[v['codex-provider'],v['codex-provider-name'],v['codex-base-url'],v['codex-env-key'],v['codex-model']]
127
+ const codexProvider=providerValues.some(Boolean)?validateCodexProvider({id:v['codex-provider']||'',name:v['codex-provider-name']||v['codex-provider']||'',baseUrl:v['codex-base-url']||'',envKey:v['codex-env-key']||'',models:v['codex-model']||[]}):undefined
128
+ console.log(JSON.stringify(await createAgent({root:'/installations',hostRoot:v['host-root']||'',composeFile:v['compose-file']||'',name:v.name||'',purpose:v.purpose||'',token:token.trim(),cli:v.cli||'',image:v['relay-image'],isolation:v.isolation,codexProvider,ledgerPort:v['ledger-port']===undefined?undefined:Number(v['ledger-port'])})))
94
129
  }
95
130
  } catch (error) { console.error((error as Error).message); process.exitCode=1 }
96
131
  }
package/src/ai-cli.ts CHANGED
@@ -1,27 +1,29 @@
1
1
  import { parseArgs } from 'node:util'
2
2
  import { randomBytes } from 'node:crypto'
3
3
  import { join } from 'node:path'
4
+ import { readFile } from 'node:fs/promises'
4
5
  import { readModels, validateSelection, type AiPreset } from './ai.js'
5
6
  import { ControlStore } from './control-state.js'
6
7
 
7
- const {values,positionals}=parseArgs({allowPositionals:true,options:{help:{type:'boolean'},cli:{type:'string'},model:{type:'string'},effort:{type:'string'}}})
8
+ const {values,positionals}=parseArgs({allowPositionals:true,options:{help:{type:'boolean'},cli:{type:'string'},provider:{type:'string'},model:{type:'string'},effort:{type:'string'}}})
8
9
  if(values.help){
9
- console.log('Usage: ezenciel-agents-ai list | select --cli <installed-cli> [--model <model>] [--effort <effort>]\nChoose only values returned by list. Selection affects subsequent messages; queued work and the installation default are unchanged.')
10
+ console.log('Usage: ezenciel-agents-ai list | select --cli <installed-cli> [--provider <provider>] [--model <model>] [--effort <effort>]\nChoose only values returned by list. Selection affects subsequent messages; queued work and the installation default are unchanged.')
10
11
  process.exit(0)
11
12
  }
12
13
  if (!process.env.EZ_CONTROL_DIR) throw new Error('Use this agent’s bound control directory')
13
- const catalog=await readModels(undefined,undefined,join(process.env.EZ_CONTROL_DIR,'cli','codex'))
14
+ const catalog=await readFile(join(process.env.EZ_CONTROL_DIR,'host-executor','models.json'),'utf8')
15
+ .then(text=>JSON.parse(text)).catch(()=>readModels(undefined,undefined,join(process.env.EZ_CONTROL_DIR!,'cli','codex')))
14
16
  if(positionals[0]==='list')console.log(JSON.stringify(catalog))
15
17
  else if(positionals[0]==='select'){
16
- const preset:AiPreset={id:randomBytes(8).toString('hex'),name:[values.model||values.cli,values.effort].filter(Boolean).join(' · '),cli:values.cli||'',model:values.model,effort:values.effort}
18
+ const preset:AiPreset={id:randomBytes(8).toString('hex'),name:[values.provider,values.model||values.cli,values.effort].filter(Boolean).join(' · '),cli:values.cli||'',provider:values.provider,model:values.model,effort:values.effort}
17
19
  await validateSelection(preset,catalog)
18
20
  const control=new ControlStore(process.env.EZ_CONTROL_DIR,900000)
19
21
  const state=await control.status()
20
22
  if(!state.ai)throw new Error('Agent AI settings are not initialized')
21
- const existing=state.ai.presets.find(p=>p.cli===preset.cli&&p.model===preset.model&&p.effort===preset.effort)
23
+ const existing=state.ai.presets.find(p=>p.cli===preset.cli&&p.provider===preset.provider&&p.model===preset.model&&p.effort===preset.effort)
22
24
  const selected=existing||preset
23
25
  if(!existing)await control.savePreset(selected)
24
26
  const current=state.ai.presets.find(p=>p.id===state.ai!.selectedId)!
25
- await control.selectPreset(selected.id,state.activeSession?.sessionId??null,current.cli!==selected.cli||Boolean(state.activeSession&&!state.activeSession.cli))
27
+ await control.selectPreset(selected.id,state.activeSession?.sessionId??null,current.cli!==selected.cli||current.provider!==selected.provider||Boolean(state.activeSession&&!state.activeSession.cli))
26
28
  console.log(JSON.stringify({selected,defaultUnchanged:true,applies:'subsequent messages; queued work keeps its captured choice'}))
27
- }else throw new Error('Use list or select --cli <installed-cli> [--model <model>] [--effort <effort>]')
29
+ }else throw new Error('Use list or select --cli <installed-cli> [--provider <provider>] [--model <model>] [--effort <effort>]')
package/src/ai.ts CHANGED
@@ -6,26 +6,26 @@ import { join, delimiter } from 'node:path'
6
6
  import { executorKey, resolveExecutor } from './executor.js'
7
7
  import { desktopCodexPath } from './desktop-bridge.js'
8
8
 
9
- export type AiPreset = { id: string; name: string; cli: string; model?: string; effort?: string }
9
+ export type AiPreset = { id: string; name: string; cli: string; provider?: string; model?: string; effort?: string }
10
10
  export type ExecutionChoice = { sessionId: string; preset: AiPreset }
11
- export type ModelChoice = { cli: string; model?: string; name: string; efforts: string[] }
11
+ export type ModelChoice = { cli: string; provider?: string; model?: string; name: string; efforts: string[] }
12
12
  const safe = (s: unknown): s is string => typeof s === 'string' && /^[a-zA-Z0-9_./:-]{1,160}$/.test(s)
13
13
  export const isPreset = (p: unknown): p is AiPreset => {
14
14
  if (!p || typeof p !== 'object') return false
15
15
  const v = p as AiPreset
16
16
  return safe(v.id) && typeof v.name === 'string' && v.name.length > 0 && v.name.length <= 80 &&
17
17
  ['grok', 'codex', 'codex-gui', 'claude', 'opencode', 'agy'].includes(v.cli) &&
18
- (v.model === undefined || safe(v.model)) && (v.effort === undefined || safe(v.effort))
18
+ (v.provider === undefined || safe(v.provider)) && (v.model === undefined || safe(v.model)) && (v.effort === undefined || safe(v.effort))
19
19
  }
20
20
  export const isExecutionChoice = (v: unknown): v is ExecutionChoice => {
21
21
  const c = v as ExecutionChoice | undefined
22
22
  return Boolean(c && /^[0-9a-f-]{36}$/i.test(c.sessionId) && isPreset(c.preset))
23
23
  }
24
- export const presetLabel = (p: AiPreset) => `${p.cli} · ${p.model || 'client default'} · ${p.effort || 'default effort'}`
24
+ export const presetLabel = (p: AiPreset) => `${p.cli}${p.provider ? ` (${p.provider})` : ''} · ${p.model || 'client default'} · ${p.effort || 'default effort'}`
25
25
  // The seed delegates model selection to the native client. Project its resolved
26
26
  // settings for status without pinning future conversations to that snapshot.
27
27
  export const statusPreset = (preset: AiPreset, discovered: AiPreset[]): AiPreset =>
28
- ['codex','codex-gui'].includes(preset.cli) && !preset.model && !preset.effort
28
+ ['codex','codex-gui'].includes(preset.cli) && !preset.provider && !preset.model && !preset.effort
29
29
  ? discovered.find((candidate) => candidate.cli === preset.cli) ?? preset
30
30
  : preset
31
31
  export const initialPreset = (cli: string): AiPreset => {
@@ -87,8 +87,8 @@ export const readModels = async (home = homedir(), available = installed, codexH
87
87
  export const validateSelection = async (p: AiPreset, catalog: ModelChoice[], available = installed): Promise<void> => {
88
88
  assertEffort(p.effort, p.model, p.cli)
89
89
  if (!isPreset(p) || !(await available(p.cli))) throw new Error('This CLI is not installed.')
90
- if (!p.model && !p.effort && p.cli !== 'agy') return
91
- const model = catalog.find((m) => m.cli === p.cli && m.model === p.model)
90
+ if (!p.provider && !p.model && !p.effort && p.cli !== 'agy') return
91
+ const model = catalog.find((m) => m.cli === p.cli && m.provider === p.provider && m.model === p.model)
92
92
  if (!model || (p.effort && !model.efforts.includes(p.effort)))
93
93
  throw new Error('This model/effort is not in the installed client catalog. Refresh the client and try again; no fallback was selected.')
94
94
  }