@fastagent-sh/fastagent 0.15.0 → 0.16.1

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 (181) hide show
  1. package/README.md +14 -4
  2. package/dist/bind.d.ts +34 -0
  3. package/dist/bind.js +74 -0
  4. package/dist/channels/agentcore-limits.d.ts +7 -0
  5. package/dist/channels/agentcore-limits.js +9 -0
  6. package/dist/channels/agentcore-state.d.ts +83 -0
  7. package/dist/channels/agentcore-state.js +266 -0
  8. package/dist/channels/agentcore.d.ts +98 -0
  9. package/dist/channels/agentcore.js +260 -0
  10. package/dist/channels/busy.d.ts +23 -0
  11. package/dist/channels/busy.js +53 -0
  12. package/dist/channels/context-buffer.d.ts +5 -0
  13. package/dist/channels/context-buffer.js +5 -0
  14. package/dist/channels/feishu/context-buffer.d.ts +13 -8
  15. package/dist/channels/feishu/context-buffer.js +60 -6
  16. package/dist/channels/feishu/feishu-api.js +4 -1
  17. package/dist/channels/feishu/feishu.d.ts +0 -12
  18. package/dist/channels/feishu/feishu.js +143 -54
  19. package/dist/channels/feishu/invoke-turn.js +35 -18
  20. package/dist/channels/feishu/model.d.ts +0 -1
  21. package/dist/channels/feishu/normalize.js +0 -1
  22. package/dist/channels/feishu/parse.d.ts +21 -7
  23. package/dist/channels/feishu/parse.js +24 -7
  24. package/dist/channels/feishu/preview.js +3 -2
  25. package/dist/channels/feishu/scaffold/channel.ts +9 -8
  26. package/dist/channels/feishu/scaffold/feishu-send.ts +6 -4
  27. package/dist/channels/feishu/setup-mode.d.ts +30 -1
  28. package/dist/channels/feishu/setup-mode.js +27 -1
  29. package/dist/channels/github/github.js +8 -1
  30. package/dist/channels/http.js +1 -1
  31. package/dist/channels/lark/scaffold/channel.ts +9 -8
  32. package/dist/channels/lark/scaffold/lark-send.ts +6 -4
  33. package/dist/channels/preview-kit.d.ts +7 -1
  34. package/dist/channels/preview-kit.js +3 -2
  35. package/dist/channels/slack/parse.d.ts +16 -1
  36. package/dist/channels/slack/parse.js +46 -3
  37. package/dist/channels/slack/preview.d.ts +1 -2
  38. package/dist/channels/slack/preview.js +68 -24
  39. package/dist/channels/slack/scaffold/channel.ts +5 -5
  40. package/dist/channels/slack/slack-api.d.ts +3 -23
  41. package/dist/channels/slack/slack-api.js +6 -22
  42. package/dist/channels/slack/slack.d.ts +13 -20
  43. package/dist/channels/slack/slack.js +95 -50
  44. package/dist/channels/state.d.ts +11 -4
  45. package/dist/channels/state.js +19 -12
  46. package/dist/channels/tasks.d.ts +0 -6
  47. package/dist/channels/tasks.js +16 -1
  48. package/dist/channels/telegram/parse.d.ts +0 -7
  49. package/dist/channels/telegram/parse.js +4 -2
  50. package/dist/channels/telegram/scaffold/telegram-send.ts +6 -3
  51. package/dist/channels/telegram/telegram.js +1 -1
  52. package/dist/channels/text.d.ts +14 -0
  53. package/dist/channels/text.js +14 -0
  54. package/dist/channels/thread-participants.d.ts +21 -0
  55. package/dist/channels/thread-participants.js +132 -0
  56. package/dist/channels/turn-queue.js +7 -0
  57. package/dist/cli/add-feishu.d.ts +7 -4
  58. package/dist/cli/add-feishu.js +57 -37
  59. package/dist/cli/add-slack.d.ts +2 -1
  60. package/dist/cli/add-slack.js +6 -11
  61. package/dist/cli/commands/add.js +50 -51
  62. package/dist/cli/commands/attach.js +8 -4
  63. package/dist/cli/commands/chat.js +8 -8
  64. package/dist/cli/commands/deploy.d.ts +14 -1
  65. package/dist/cli/commands/deploy.js +330 -78
  66. package/dist/cli/commands/dev.d.ts +1 -0
  67. package/dist/cli/commands/dev.js +38 -25
  68. package/dist/cli/commands/fire.js +15 -16
  69. package/dist/cli/commands/info.js +36 -29
  70. package/dist/cli/commands/init.d.ts +1 -1
  71. package/dist/cli/commands/init.js +65 -53
  72. package/dist/cli/commands/invoke.js +9 -6
  73. package/dist/cli/commands/login.js +35 -21
  74. package/dist/cli/commands/schedule.js +6 -8
  75. package/dist/cli/commands/start.d.ts +1 -0
  76. package/dist/cli/commands/start.js +101 -37
  77. package/dist/cli/commands/tool.js +30 -18
  78. package/dist/cli/fail.d.ts +17 -0
  79. package/dist/cli/fail.js +24 -0
  80. package/dist/cli/program.js +66 -36
  81. package/dist/cli/serve.d.ts +52 -8
  82. package/dist/cli/serve.js +133 -32
  83. package/dist/cli/shared.d.ts +21 -2
  84. package/dist/cli/shared.js +44 -18
  85. package/dist/deploy/agentcore/plan.d.ts +117 -0
  86. package/dist/deploy/agentcore/plan.js +721 -0
  87. package/dist/deploy/agentcore/run.d.ts +73 -0
  88. package/dist/deploy/agentcore/run.js +412 -0
  89. package/dist/deploy/agentcore/zip.d.ts +17 -0
  90. package/dist/deploy/agentcore/zip.js +68 -0
  91. package/dist/deploy/container.d.ts +26 -25
  92. package/dist/deploy/container.js +93 -89
  93. package/dist/deploy/docker/plan.d.ts +1 -1
  94. package/dist/deploy/docker/plan.js +12 -17
  95. package/dist/deploy/fly/plan.d.ts +2 -0
  96. package/dist/deploy/fly/plan.js +27 -19
  97. package/dist/deploy/fly/run.d.ts +12 -1
  98. package/dist/deploy/fly/run.js +36 -2
  99. package/dist/deploy/preflight.d.ts +11 -5
  100. package/dist/deploy/preflight.js +235 -65
  101. package/dist/deploy/railway/plan.d.ts +7 -0
  102. package/dist/deploy/railway/plan.js +41 -16
  103. package/dist/deploy/railway/run.d.ts +8 -1
  104. package/dist/deploy/railway/run.js +7 -2
  105. package/dist/deploy/runner.d.ts +5 -2
  106. package/dist/deploy/runner.js +9 -3
  107. package/dist/dev-supervisor.d.ts +11 -8
  108. package/dist/dev-supervisor.js +53 -51
  109. package/dist/engines/pi/auth.d.ts +8 -7
  110. package/dist/engines/pi/auth.js +12 -10
  111. package/dist/engines/pi/channel.d.ts +1 -1
  112. package/dist/engines/pi/channel.js +5 -5
  113. package/dist/engines/pi/chat.js +2 -2
  114. package/dist/engines/pi/config.d.ts +12 -48
  115. package/dist/engines/pi/config.js +29 -110
  116. package/dist/engines/pi/create.d.ts +32 -24
  117. package/dist/engines/pi/create.js +47 -23
  118. package/dist/engines/pi/definition.d.ts +7 -26
  119. package/dist/engines/pi/definition.js +8 -54
  120. package/dist/engines/pi/harness.d.ts +19 -5
  121. package/dist/engines/pi/harness.js +3 -5
  122. package/dist/engines/pi/login.d.ts +1 -1
  123. package/dist/engines/pi/models.d.ts +3 -3
  124. package/dist/engines/pi/models.js +1 -1
  125. package/dist/engines/pi/{workspace.d.ts → open.d.ts} +31 -25
  126. package/dist/engines/pi/{workspace.js → open.js} +27 -29
  127. package/dist/engines/pi/read-image.d.ts +4 -0
  128. package/dist/engines/pi/read-image.js +62 -0
  129. package/dist/engines/pi/search-tools.d.ts +6 -4
  130. package/dist/engines/pi/search-tools.js +3 -1
  131. package/dist/engines/pi/session-builder.d.ts +2 -2
  132. package/dist/engines/pi/session-builder.js +18 -13
  133. package/dist/engines/pi/tool.d.ts +13 -5
  134. package/dist/engines/pi/tool.js +4 -0
  135. package/dist/engines/pi/wake-tool.d.ts +3 -3
  136. package/dist/env.d.ts +16 -4
  137. package/dist/env.js +43 -5
  138. package/dist/host/node.d.ts +4 -2
  139. package/dist/host/node.js +2 -1
  140. package/dist/loader.d.ts +2 -2
  141. package/dist/loader.js +3 -3
  142. package/dist/log.d.ts +1 -1
  143. package/dist/log.js +1 -1
  144. package/dist/paths.d.ts +138 -0
  145. package/dist/paths.js +326 -0
  146. package/dist/pi.d.ts +2 -2
  147. package/dist/pi.js +2 -2
  148. package/dist/runtime.d.ts +7 -5
  149. package/dist/runtime.js +2 -2
  150. package/dist/scaffold/add-channel.d.ts +7 -3
  151. package/dist/scaffold/add-channel.js +55 -29
  152. package/dist/scaffold/init.d.ts +32 -41
  153. package/dist/scaffold/init.js +161 -185
  154. package/dist/scaffold/templates/env.example +15 -6
  155. package/dist/scaffold/templates/fastagent.config.mjs +1 -1
  156. package/dist/scaffold/templates/gitignore +14 -6
  157. package/dist/scaffold/templates/persona.md +4 -2
  158. package/dist/scaffold/templates/secrets.gitignore +5 -0
  159. package/dist/scaffold/templates.d.ts +1 -7
  160. package/dist/scaffold/templates.js +3 -25
  161. package/dist/scaffold/vendor-skill.d.ts +2 -2
  162. package/dist/scaffold/vendor-skill.js +13 -13
  163. package/dist/schedule/discover.js +4 -4
  164. package/dist/schedule/scheduler.d.ts +40 -1
  165. package/dist/schedule/scheduler.js +89 -56
  166. package/dist/schedule/state.js +1 -1
  167. package/dist/schedule/wake-alarm.d.ts +47 -0
  168. package/dist/schedule/wake-alarm.js +136 -0
  169. package/dist/schedule/wakeups.d.ts +1 -0
  170. package/dist/schedule/wakeups.js +18 -0
  171. package/dist/tunnel.d.ts +3 -3
  172. package/dist/tunnel.js +7 -7
  173. package/package.json +7 -4
  174. package/dist/channels/feishu/owned-threads.d.ts +0 -7
  175. package/dist/channels/feishu/owned-threads.js +0 -47
  176. package/dist/channels/slack/owned-threads.d.ts +0 -6
  177. package/dist/channels/slack/owned-threads.js +0 -43
  178. package/dist/scaffold/templates/gitignore.agentdir-root +0 -5
  179. package/dist/scaffold/templates/gitignore.kit +0 -2
  180. package/dist/workspace.d.ts +0 -9
  181. package/dist/workspace.js +0 -45
@@ -4,77 +4,139 @@
4
4
  */
5
5
  import { mkdir, writeFile } from "node:fs/promises";
6
6
  import { dirname, resolve } from "node:path";
7
- import { authSeedBytes } from "../../deploy/fly/run.js";
7
+ import { authSeedBytes, collectAuthSeed } from "../../deploy/fly/run.js";
8
8
  import { loadDotEnv } from "../../env.js";
9
9
  import { resolveAuthPath, resolveSessionsDirOverride } from "../../engines/pi/config.js";
10
+ import { resolveSecretsDir, workspaceHint } from "../../paths.js";
10
11
  import { isUnderDir } from "../../engines/pi/definition.js";
11
12
  import { reportDefinitionWarnings, reportModuleLoadFailures, reportToolCollisions } from "../../engines/pi/report.js";
12
- import { createPiAgentFromWorkspace } from "../../engines/pi/workspace.js";
13
+ import { createPiAgentFromDir } from "../../engines/pi/open.js";
13
14
  import { log, setLogLevel } from "../../log.js";
15
+ import { createWakeAlarmSink, reconcileWakeAlarms } from "../../schedule/wake-alarm.js";
16
+ import { setWakeupsSink } from "../../schedule/wakeups.js";
14
17
  import { logAgentLoop } from "../../observe.js";
15
18
  import { installProxyFetch } from "../../proxy.js";
16
- import { exists } from "../../scaffold/init.js";
17
- import { failStartup } from "../fail.js";
18
- import { maybeTunnel, mountSessionControl, routesFor, serve, startSchedules } from "../serve.js";
19
- import { parsePort, reportAuth, resolveFirstRunModel } from "../shared.js";
19
+ import { exists } from "../../paths.js";
20
+ import { bindAddress } from "../../bind.js";
21
+ import { failStartup, placementOrExit } from "../fail.js";
22
+ import { assertTunnelBindable, maybeTunnel, mountAgentcore, mountSessionControl, routesFor, serve, startSchedules, } from "../serve.js";
23
+ import { parseBind, parsePort, reportAuth, reportLine, resolveFirstRunModel, reportWorkspaceHint } from "../shared.js";
20
24
  export async function runStart(dirArg, opts) {
21
25
  const dir = resolve(dirArg);
22
- setLogLevel("info"); // production posture: info+, the debug turn trace (and its end-user content) gated out
26
+ // Flag validation first: a bad --port is a USAGE error (exit 2), and reporting it must not depend on
27
+ // the directory being an agent (which is a runtime/environment failure, exit 1).
23
28
  const portFlag = parsePort(opts.port, "--port", "flag");
24
- loadDotEnv(dir);
29
+ const bindFlag = parseBind(opts.bind);
30
+ const placement = placementOrExit(dir);
31
+ setLogLevel("info"); // production posture: info+, the debug turn trace (and its end-user content) gated out
32
+ loadDotEnv(placement.agentDir);
25
33
  installProxyFetch();
26
- await resolveFirstRunModel(dir, opts);
34
+ await resolveFirstRunModel(placement.agentDir, opts);
27
35
  // A `deploy --run` may carry the operator's local credential as FASTAGENT_AUTH_SEED —
28
- // materialize it onto the writable state root BEFORE the opener resolves auth (once, absent-only).
36
+ // materialize it into the writable secrets dir BEFORE the opener resolves auth (once, absent-only).
29
37
  // Same resolveAuthPath the opener uses — ONE owner of the flag > env > default chain.
30
- await maybeSeedAuth(resolveAuthPath(dir, opts.authPath));
38
+ await maybeSeedAuth(resolveAuthPath(placement.agentDir, opts.authPath));
31
39
  // The same opener dev uses (single assembly source), just no watch.
32
40
  const sessionsDirOverride = resolveSessionsDirOverride(opts.sessionsDir);
33
- const { agent, definition, agentDir, config, modelSpec, stateRoot, sessionsDir, authPath, toolNames, deferredToolNames, toolCollisions, toolFailures, sessionControl, } = await createPiAgentFromWorkspace(dir, {
41
+ const { agent, definition, agentDir, workspace, config, modelSpec, stateRoot, sessionsDir, authPath, toolNames, deferredToolNames, toolCollisions, toolFailures, sessionControl, } = await createPiAgentFromDir(dir, {
34
42
  model: opts.model,
35
43
  sessionsDir: sessionsDirOverride,
36
44
  authPath: opts.authPath,
37
45
  serving: true, // long-running serve: the scheduler poller runs (wake mounts iff config.selfSchedule)
38
46
  }).catch(failStartup);
39
- log.info(`[fastagent] start: ${dir}`);
40
- if (agentDir !== dir)
41
- log.info(`[fastagent] agent: ${agentDir}`);
42
- log.info(`[fastagent] model: ${modelSpec}${config.thinkingLevel ? ` (thinking: ${config.thinkingLevel})` : ""}`);
47
+ reportLine("agent", agentDir);
48
+ reportLine("workspace", workspace);
49
+ reportWorkspaceHint(workspaceHint({ agentDir, workspace }));
50
+ reportLine("model", `${modelSpec}${config.thinkingLevel ? ` (thinking: ${config.thinkingLevel})` : ""}`);
43
51
  await reportAuth(modelSpec, authPath);
44
- log.info(`[fastagent] context: ${definition.contextFiles.map((f) => f.path).join(", ") || "(none)"}`);
52
+ reportLine("context", definition.contextFiles.map((f) => f.path).join(", ") || "(none)");
45
53
  if (definition.persona)
46
- log.info(`[fastagent] persona: persona.md`);
47
- log.info(`[fastagent] skills: ${definition.skills.map((s) => s.name).join(", ") || "(none)"}`);
54
+ reportLine("persona", "persona.md");
55
+ reportLine("skills", definition.skills.map((s) => s.name).join(", ") || "(none)");
48
56
  if (toolNames.length > 0)
49
- log.info(`[fastagent] tools: ${toolNames.join(", ")}`);
57
+ reportLine("tools", toolNames.join(", "));
50
58
  if (deferredToolNames.length > 0) {
51
- log.info(`[fastagent] deferred: ${deferredToolNames.join(", ")} (activated via search_tools)`);
59
+ reportLine("deferred", `${deferredToolNames.join(", ")} (activated via search_tools)`);
52
60
  }
53
61
  reportToolCollisions(toolCollisions);
54
62
  reportModuleLoadFailures(toolFailures);
55
- log.info(`[fastagent] state: ${stateRoot}`);
56
- log.info(`[fastagent] sessions: ${sessionsDir}`);
57
- // State defaults under the definition dir, which a redeploy may replace wholesale. Gate on where the
58
- // root ACTUALLY resolved (in-tree?), not on the raw env var: an empty `FASTAGENT_STATE_DIR=""` reads
59
- // as unset (resolveStateRoot) and still lands in-tree, so a raw `=== undefined` check would wrongly
60
- // silence the warning. A sessions/auth override to a volume does not help — channel state (the
61
- // telegram turn/context files replay depends on) is still in-tree.
62
- if (isUnderDir(stateRoot, dir)) {
63
- log.info(`[fastagent] note: state (auth, sessions, channel state) lives under the definition dir; point ` +
63
+ reportLine("state", stateRoot);
64
+ reportLine("sessions", sessionsDir);
65
+ // State defaults under the agent dir, which a redeploy may replace wholesale. Gate on where the
66
+ // state root ACTUALLY resolved (inside the agent dir?), not on the raw env var: an empty
67
+ // `FASTAGENT_STATE_DIR=""` reads as unset (resolveStateRoot) and still lands in-agent, so a raw
68
+ // `=== undefined` check would wrongly silence the warning. A sessions override to a volume does not
69
+ // help — channel state (the telegram turn/context files replay depends on) is still in-agent.
70
+ // (auth.json is NOT under the state root — it lives in the secrets dir, resolveSecretsDir.)
71
+ if (isUnderDir(stateRoot, agentDir)) {
72
+ log.info(`[fastagent] note: state (sessions, channel state) lives under the definition dir; point ` +
64
73
  `FASTAGENT_STATE_DIR at a persistent volume so a redeploy that replaces the dir does not wipe it.`);
65
74
  }
75
+ // The secrets dir is the SAME trap on a different lifecycle: auth.json is MACHINE-WRITTEN (OAuth
76
+ // rotation), so the copy under the definition dir is the only valid one — a redeploy that replaces
77
+ // the dir loses a credential no re-seed can restore. An independent check on purpose: moving ONE
78
+ // of the two to a volume must not silence the note about the other.
79
+ if (isUnderDir(resolveSecretsDir(agentDir), agentDir)) {
80
+ log.info(`[fastagent] note: secrets (.env, rotated auth.json) live under the definition dir; point ` +
81
+ `FASTAGENT_SECRETS_DIR at a persistent volume so a redeploy that replaces the dir does not wipe them.`);
82
+ }
66
83
  reportDefinitionWarnings(definition.collisions, definition.diagnostics);
84
+ // AgentCore Runtime posture (FASTAGENT_AGENTCORE=1, set by the generated deploy artifacts): the
85
+ // adapter (POST /invocations + GET /ping) is the container's only reachable surface, and cron
86
+ // slots arrive from the external clock through it — so no resident cron timers. In particular,
87
+ // do NOT mount the ordinary unauthenticated POST /invoke fallback: a selfSchedule-only topology
88
+ // needs a public Function URL for wake callbacks, and its forwarder can relay arbitrary paths.
89
+ const agentcore = process.env.FASTAGENT_AGENTCORE === "1";
67
90
  // Same debug turn trace as dev; gated out here by the info level (see dev.ts serveOnce).
68
91
  const traced = logAgentLoop(agent);
69
- const routed = await routesFor(agentDir, traced, stateRoot, sessionControl).catch(failStartup);
92
+ const routed = await routesFor(agentDir, traced, stateRoot, sessionControl, { builtinInvoke: !agentcore }).catch(failStartup);
93
+ // `http.host` enters here the way the flag enters `parseBind` — through `bindAddress`, so a
94
+ // configured `localhost` is an ADDRESS by the time anything binds, renders or dials it.
95
+ const configured = config.http?.host;
96
+ const host = bindFlag ?? (configured === undefined ? undefined : bindAddress(configured));
97
+ assertTunnelBindable(host, opts.tunnel ?? false, bindFlag ? "flag" : "config");
70
98
  const withControl = mountSessionControl(routed.routes, sessionControl, stateRoot, {
71
99
  tunnel: opts.tunnel ?? false,
72
100
  agent: traced,
101
+ host,
73
102
  });
74
- await startSchedules(agentDir, traced, stateRoot, config.selfSchedule ?? false);
75
- serve({ ...routed, routes: withControl.routes }, portFlag ?? parsePort(process.env.PORT, "PORT env", "env") ?? config.http?.port ?? 8787, (p) => {
103
+ // AgentCore + selfSchedule: register the wake-ALARM sink BEFORE the scheduler starts — the boot
104
+ // wake pump may advance a recurring entry (a store save) and that save must already re-arm its
105
+ // alarm. The secret arrives via the stack (FASTAGENT_WAKE_SECRET); without it the deployment
106
+ // degrades to awake-only wakes — warned, never silent.
107
+ let onStateReady;
108
+ if (agentcore && config.selfSchedule) {
109
+ const wakeSecret = process.env.FASTAGENT_WAKE_SECRET;
110
+ if (wakeSecret) {
111
+ const sink = createWakeAlarmSink({ secret: wakeSecret });
112
+ setWakeupsSink(sink);
113
+ // NOT here: at boot the state mount is whatever the platform just provisioned — after a runtime
114
+ // version update that is EMPTY, so a reconcile now would see no pending wake-ups and conclude
115
+ // there is nothing to re-arm. It runs once the snapshot has been restored (mountAgentcore).
116
+ onStateReady = () => reconcileWakeAlarms(stateRoot, sink);
117
+ log.info(`[fastagent] wake alarms: EventBridge-backed via the forwarder`);
118
+ }
119
+ else {
120
+ log.warn(`[fastagent] FASTAGENT_WAKE_SECRET is not set — wake-ups fire only while a session is awake ` +
121
+ `(redeploy with the current template to fix)`);
122
+ }
123
+ }
124
+ const schedules = await startSchedules(agentDir, traced, stateRoot, config.selfSchedule ?? false, {
125
+ externalClock: agentcore,
126
+ });
127
+ let routes = withControl.routes;
128
+ if (agentcore) {
129
+ try {
130
+ routes = mountAgentcore(routes, { agent: traced, stateRoot, schedules, onStateReady });
131
+ }
132
+ catch (e) {
133
+ failStartup(e);
134
+ }
135
+ log.info(`[fastagent] agentcore: serving POST /invocations + GET /ping (FASTAGENT_AGENTCORE=1)`);
136
+ }
137
+ serve({ ...routed, routes }, { port: portFlag ?? parsePort(process.env.PORT, "PORT env", "env") ?? config.http?.port ?? 8787, host }, (p) => {
76
138
  withControl.announce(p);
77
- maybeTunnel(dir, routed.routeChannels, p, opts.tunnel ?? false, stateRoot);
139
+ maybeTunnel(agentDir, routed.routeChannels, p, opts.tunnel ?? false, stateRoot);
78
140
  });
79
141
  // No graceful drain: webhook turns run fire-and-forget; SIGTERM just exits mid-turn. Whether an
80
142
  // in-flight turn is LOST depends on the channel: the Telegram channel persists turn intent pre-ACK
@@ -82,13 +144,15 @@ export async function runStart(dirArg, opts) {
82
144
  // channels have no such layer, so their in-flight turns are still lost (the asker re-invokes).
83
145
  }
84
146
  /**
85
- * Materialize `FASTAGENT_AUTH_SEED` (base64 of an auth.json, set by `deploy --run`) onto the
86
- * writable state root ONCE — only when the seed is set AND the auth file is absent, so a refreshed
147
+ * Materialize `FASTAGENT_AUTH_SEED` (base64 of an auth.json, set by `deploy --run`) into the
148
+ * writable secrets dir ONCE — only when the seed is set AND the auth file is absent, so a refreshed
87
149
  * volume copy is never clobbered by the stale seed. Lets a deploy carry the operator's local
88
150
  * OAuth/API credential so the box runs on the SAME subscription. No-op locally (the seed is unset).
89
151
  */
90
152
  async function maybeSeedAuth(authPath) {
91
- const bytes = authSeedBytes(process.env.FASTAGENT_AUTH_SEED, await exists(authPath));
153
+ // collectAuthSeed: the seed may arrive CHUNKED (FASTAGENT_AUTH_SEED + _2…) on hosts with a small
154
+ // env-value max length (AgentCore); single-var hosts are unchanged.
155
+ const bytes = authSeedBytes(collectAuthSeed(process.env), await exists(authPath));
92
156
  if (!bytes)
93
157
  return;
94
158
  await mkdir(dirname(authPath), { recursive: true });
@@ -1,20 +1,23 @@
1
1
  /** `fastagent tool <name> '<json>' [dir]`: run one tool's body directly with JSON args — no model. */
2
2
  import { resolve } from "node:path";
3
+ import { NodeExecutionEnv } from "@earendil-works/pi-agent-core/node";
3
4
  import { loadDotEnv } from "../../env.js";
4
- import { loadConfig, resolveAgentDir } from "../../engines/pi/config.js";
5
- import { resolveWorkspaceTools } from "../../engines/pi/create.js";
5
+ import { loadConfig } from "../../engines/pi/config.js";
6
+ import { resolveAgentTools } from "../../engines/pi/create.js";
6
7
  import { reportModuleLoadFailures } from "../../engines/pi/report.js";
7
8
  import { turnContext } from "../../engines/pi/tool-context.js";
8
- import { failStartup, failUsage } from "../fail.js";
9
+ import { failStartup, failUsage, placementOrExit } from "../fail.js";
9
10
  export async function runTool(name, argsJson, dirArg) {
10
- const toolDir = resolve(dirArg);
11
- loadDotEnv(toolDir); // a tool may read a key from .env
12
- const { config } = await loadConfig(toolDir).catch(failStartup);
11
+ // Argument shape first: malformed JSON is a USAGE error (exit 2), independent of whether the
12
+ // directory is an agent (a runtime failure, exit 1).
13
+ const args = parseToolArgs(argsJson);
14
+ const { agentDir, workspace } = placementOrExit(resolve(dirArg));
15
+ loadDotEnv(agentDir); // a tool may read a key from .env
16
+ const { config } = await loadConfig(agentDir).catch(failStartup);
13
17
  // The same tool set dev/start mount (defaults + config.tools + discovered, deduped), so the runner
14
- // exercises exactly what gets served — a shadowed tool is surfaced, not silently run. Resolve agentDir
15
- // like the openers so `fastagent tool` finds the SAME tools/ as dev/start when config.agentDir is set.
16
- const agentDir = resolveAgentDir(toolDir, config);
17
- const { tools, toolCollisions, toolFailures } = await resolveWorkspaceTools(config, agentDir, toolDir).catch(failStartup);
18
+ // exercises exactly what gets served — a shadowed tool is surfaced, not silently run. Resolve the
19
+ // placement like the openers, so `fastagent tool` finds the SAME tools/ as dev/start.
20
+ const { tools, toolCollisions, toolFailures } = await resolveAgentTools(config, agentDir).catch(failStartup);
18
21
  for (const c of toolCollisions) {
19
22
  console.error(`[fastagent] warn: tool "${c.name}" (${c.source}) is shadowed by a default/config tool — not mounted`);
20
23
  }
@@ -23,16 +26,25 @@ export async function runTool(name, argsJson, dirArg) {
23
26
  if (!tool) {
24
27
  failStartup(new Error(`unknown tool "${name}". available: ${tools.map((t) => t.name).join(", ") || "(none)"}`));
25
28
  }
26
- let args;
27
- try {
28
- args = JSON.parse(argsJson);
29
- }
30
- catch {
31
- failUsage(`invalid JSON args: ${argsJson}`); // malformed input syntax = usage error, exit 2
32
- }
33
- const result = await turnContext.run({ cwd: toolDir }, () => tool.execute(`cli-${name}`, args)).catch(failStartup);
29
+ // Two contexts, because the two tool families read different ones and this command must serve both
30
+ // exactly as serving does: fastagent's own tools take cwd/session/activation from `turnContext`
31
+ // (AsyncLocalStorage), and pi's default coding tools take the ExecutionEnv from the harness's TOOL
32
+ // context — which no harness supplies here, so this stands in for it, rooted at the same workspace.
33
+ const env = new NodeExecutionEnv({ cwd: workspace });
34
+ const result = await turnContext
35
+ .run({ cwd: workspace }, () => tool.execute(`cli-${name}`, args, undefined, undefined, { env }))
36
+ .catch(failStartup);
34
37
  const out = result?.details !== undefined
35
38
  ? result.details
36
39
  : (result?.content ?? []).map((c) => ("text" in c ? c.text : "")).join("");
37
40
  console.log(typeof out === "string" ? out : JSON.stringify(out, null, 2));
38
41
  }
42
+ /** Parse the CLI's JSON args blob; malformed input syntax is a usage error (exit 2). */
43
+ function parseToolArgs(argsJson) {
44
+ try {
45
+ return JSON.parse(argsJson);
46
+ }
47
+ catch {
48
+ failUsage(`invalid JSON args: ${argsJson}`);
49
+ }
50
+ }
@@ -1,3 +1,4 @@
1
+ import { type ResolvedPlacement } from "../paths.ts";
1
2
  /**
2
3
  * The ONE error prefix every error message carries — bold red when stderr renders color, plain
3
4
  * otherwise. Errors are the only place the CLI uses color at all.
@@ -9,6 +10,22 @@ export declare function errorPrefix(colors?: boolean): string;
9
10
  * Shared by the kernel and the command modules; exit 1 (runtime failure).
10
11
  */
11
12
  export declare function failStartup(error: unknown): never;
13
+ /**
14
+ * THE placement entry point for commands: resolve `dir`, or exit 1 with the one-line refusal. Every
15
+ * command that needs an agent goes through this — the try/catch was hand-repeated at sixteen call
16
+ * sites, which is sixteen chances to forget it (`dev`'s supervisor did, and surfaced a raw stack).
17
+ *
18
+ * The catch is what makes it a function at all: placement resolves SYNCHRONOUSLY, before any promise
19
+ * exists, so it cannot ride the `.catch(failStartup)` every async startup chain carries — and its
20
+ * refusals ("not a fastagent agent", plus the two dead ends with their own exits) are user-fixable,
21
+ * which means a one-line `Error:` and exit 1, never a stack.
22
+ *
23
+ * Not every command calls it — and the exceptions are the useful part of this note. `init` CREATES the
24
+ * agent (it must run where there is none). `models` is directory-independent. `login` needs one only for
25
+ * the project-level credential and falls back to the global one, and `attach --url/--token` reads
26
+ * nothing local. Everything else needs an agent, so it comes through here.
27
+ */
28
+ export declare function placementOrExit(dir: string): ResolvedPlacement;
12
29
  /**
13
30
  * A usage error the parser could not catch (a bad value shape, an invalid flag/argument combination
14
31
  * discovered in a command body): print the message and exit 2 — the same class as a parse error.
package/dist/cli/fail.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { resolvePlacement } from "../paths.js";
1
2
  /** stderr renders color: a color TTY, with Node's `hasColors()` carrying the NO_COLOR/TERM=dumb veto. */
2
3
  function stderrHasColors() {
3
4
  return process.stderr.isTTY === true && (process.stderr.hasColors?.() ?? false);
@@ -21,6 +22,29 @@ export function failStartup(error) {
21
22
  console.error(errorPrefix(), error);
22
23
  process.exit(1);
23
24
  }
25
+ /**
26
+ * THE placement entry point for commands: resolve `dir`, or exit 1 with the one-line refusal. Every
27
+ * command that needs an agent goes through this — the try/catch was hand-repeated at sixteen call
28
+ * sites, which is sixteen chances to forget it (`dev`'s supervisor did, and surfaced a raw stack).
29
+ *
30
+ * The catch is what makes it a function at all: placement resolves SYNCHRONOUSLY, before any promise
31
+ * exists, so it cannot ride the `.catch(failStartup)` every async startup chain carries — and its
32
+ * refusals ("not a fastagent agent", plus the two dead ends with their own exits) are user-fixable,
33
+ * which means a one-line `Error:` and exit 1, never a stack.
34
+ *
35
+ * Not every command calls it — and the exceptions are the useful part of this note. `init` CREATES the
36
+ * agent (it must run where there is none). `models` is directory-independent. `login` needs one only for
37
+ * the project-level credential and falls back to the global one, and `attach --url/--token` reads
38
+ * nothing local. Everything else needs an agent, so it comes through here.
39
+ */
40
+ export function placementOrExit(dir) {
41
+ try {
42
+ return resolvePlacement(dir);
43
+ }
44
+ catch (error) {
45
+ failStartup(error);
46
+ }
47
+ }
24
48
  /**
25
49
  * A usage error the parser could not catch (a bad value shape, an invalid flag/argument combination
26
50
  * discovered in a command body): print the message and exit 2 — the same class as a parse error.
@@ -8,14 +8,18 @@ import { fastagentVersion } from "../version.js";
8
8
  import { buildProgram } from "./kernel.js";
9
9
  // Help groups (clig: most common commands first) — the authoring loop leads, operations close.
10
10
  // Shared flags — same name, same meaning, on every command that supports them (clig: consistency).
11
- const DIR_ARG = { name: "[dir]", description: "workspace directory", default: "." };
11
+ const DIR_ARG = {
12
+ name: "[dir]",
13
+ description: "workspace directory (the agent is here, or in a directory inside it)",
14
+ default: ".",
15
+ };
12
16
  const MODEL = {
13
17
  flags: "--model <provider/modelId>",
14
18
  description: "model override (precedence: --model > FASTAGENT_MODEL > config)",
15
19
  };
16
20
  const AUTH_PATH = {
17
21
  flags: "--auth-path <file>",
18
- description: "credentials file (default: <state root>/auth.json; env: FASTAGENT_AUTH_PATH)",
22
+ description: "credentials file (default: <agent dir>/.secrets/auth.json; env: FASTAGENT_AUTH_PATH)",
19
23
  };
20
24
  const JSON_FLAG = { flags: "--json", description: "machine-readable JSON output" };
21
25
  const NO_INPUT = {
@@ -23,6 +27,10 @@ const NO_INPUT = {
23
27
  description: "never prompt (CI/scripts) — missing information becomes an error instead of a question",
24
28
  };
25
29
  const PORT = { flags: "--port <n>", description: "HTTP port" };
30
+ const BIND = {
31
+ flags: "--bind <addr>",
32
+ description: "bind address (default: all interfaces; 127.0.0.1 keeps it off the LAN)",
33
+ };
26
34
  const TUNNEL = {
27
35
  flags: "--tunnel",
28
36
  description: "expose a public HTTPS URL via a Cloudflare quick tunnel (needs cloudflared) and auto-register " +
@@ -32,31 +40,43 @@ const TUNNEL = {
32
40
  const init = {
33
41
  name: "init",
34
42
  summary: "scaffold a runnable agent and install its dependencies",
35
- description: "Scaffold a runnable agent in dir (default .) and run npm install. Default is a self-iterating " +
36
- "agent: persona.md (its identity), a writing-great-skills example skill, a fetch-url code tool, " +
37
- "config, package.json, .gitignore. Never overwrites existing files; an existing AGENTS.md is kept " +
38
- "as project context.",
43
+ description: "Scaffold a runnable agent and run npm install. By default the agent goes into ./fastagent/ in dir " +
44
+ "(default .; --agent-dir names it otherwise) the rest of the directory gets zero writes, and it is " +
45
+ "the WORKSPACE the agent works ON when you point fastagent there. Default content is a " +
46
+ "self-iterating agent: persona.md (its identity), a writing-great-skills " +
47
+ "example skill, a fetch-url code tool, config, package.json, .gitignore. An existing AGENTS.md is " +
48
+ "kept as project context.",
39
49
  args: [DIR_ARG],
40
50
  flags: [
41
51
  { flags: "--minimal", description: "persona.md + the example skill + config only (no code tool / package.json)" },
42
52
  { flags: "--no-install", description: "scaffold everything but skip npm install" },
43
- { flags: "--flat", description: "force the flat layout (skip host-signal detection)", conflicts: ["agentDir"] },
44
- { flags: "--agent-dir <name>", description: "force the agent kit into ./<name>" },
53
+ { flags: "--agent-dir <name>", description: "name the agent directory (default fastagent; . = dir itself)" },
54
+ {
55
+ flags: "--flat",
56
+ description: "alias for --agent-dir . — the directory IS the agent; keeps existing files",
57
+ // Two spellings of ONE knob: `--flat --agent-dir bot` names the same thing twice with different
58
+ // values, which is a usage error, not a precedence question to settle silently.
59
+ conflicts: ["agentDir"],
60
+ },
45
61
  ],
46
62
  examples: [
47
- { cmd: "fastagent init my-agent", note: "a new agent dir, ready to dev" },
48
- { cmd: "fastagent init", note: "initialize the current directory" },
63
+ { cmd: "fastagent init", note: "the agent lands in ./fastagent/" },
64
+ { cmd: "fastagent init my-project", note: "my-project/fastagent/ (created)" },
65
+ { cmd: "fastagent init . --agent-dir bot", note: "./bot/ — any name works" },
66
+ { cmd: "fastagent init . --flat", note: "this repo IS the agent" },
49
67
  ],
50
- notes: 'Layout: flat by default ("a directory is an agent"); when an existing toolchain/deploy claims ' +
51
- "the directory (tsconfig/framework config, a non-JS build manifest like " +
52
- "go.mod/pyproject.toml/Cargo.toml, Dockerfile/fly/railway, or occupied tools/, channels/, or " +
53
- "skills/), the kit goes into ./agent and config.agentDir points there the reason is printed, " +
54
- "no prompt.",
68
+ notes: "An agent is a directory holding a fastagent.config.* never its NAME, so --agent-dir can call it " +
69
+ "anything (the name decides only which agent answers when a workspace holds several: see " +
70
+ "FASTAGENT_AGENT). What the agent works ON (its cwd, where its AGENTS.md context is read from) is " +
71
+ "whatever directory you later point fastagent at: point at the project and the agent inside it " +
72
+ "serves with the project as its workspace; point at the agent directory (all a deployed box may " +
73
+ "hold) and it works on itself. A directory resolves to ONE agent, at it or one level inside.",
55
74
  run: async (args, f) => (await import("./commands/init.js")).runInit(args[0], {
56
75
  minimal: f.minimal === true,
57
76
  install: f.install !== false,
58
- flat: f.flat === true,
59
- agentDir: f.agentDir,
77
+ // `--flat` is the spelling for the common case of the same knob (they conflict, so only one is
78
+ // ever set); both land in ONE value, so the scaffolder never sees two ways to say ".".
79
+ agentDir: f.flat === true ? "." : typeof f.agentDir === "string" ? f.agentDir : undefined,
60
80
  }),
61
81
  };
62
82
  const dev = {
@@ -64,11 +84,12 @@ const dev = {
64
84
  summary: "serve the agent locally, restarting on code edits",
65
85
  description: "Assemble the agent in dir (default .) and serve a local HTTP channel. persona.md/AGENTS.md/skills " +
66
86
  "are re-read every turn (edits go live next turn); edits to code inputs — tools/, channels/, " +
67
- "fastagent.config.*, package.json, .env — restart the worker. Files the agent writes as work " +
68
- "product never trigger a restart.",
87
+ "fastagent.config.*, package.json, .secrets/.env — restart the worker. Files the agent writes as " +
88
+ "work product never trigger a restart.",
69
89
  args: [DIR_ARG],
70
90
  flags: [
71
91
  PORT,
92
+ BIND,
72
93
  MODEL,
73
94
  AUTH_PATH,
74
95
  { flags: "--no-watch", description: "serve once, no file-watching" },
@@ -81,6 +102,7 @@ const dev = {
81
102
  ],
82
103
  run: async (args, f) => (await import("./commands/dev.js")).runDev(args[0], {
83
104
  port: f.port,
105
+ bind: f.bind,
84
106
  model: f.model,
85
107
  authPath: f.authPath,
86
108
  watch: f.watch !== false,
@@ -202,6 +224,7 @@ const start = {
202
224
  args: [DIR_ARG],
203
225
  flags: [
204
226
  PORT,
227
+ BIND,
205
228
  MODEL,
206
229
  { flags: "--sessions-dir <dir>", description: "sessions directory override" },
207
230
  AUTH_PATH,
@@ -214,16 +237,18 @@ const start = {
214
237
  ],
215
238
  notes: "Precedence chains:\n" +
216
239
  " port: --port > PORT env > fastagent.config.ts http.port > 8787\n" +
217
- " state: FASTAGENT_STATE_DIR > <dir>/.fastagent the ONE machine-state\n" +
218
- " root (auth, sessions, channel state all derive from it); point\n" +
219
- " it at a mounted volume so a redeploy that replaces the\n" +
220
- " directory never wipes state\n" +
240
+ " bind: --bind > fastagent.config.ts http.host > all interfaces\n" +
241
+ " state: FASTAGENT_STATE_DIR > <agent dir>/.state mutable machine state\n" +
242
+ " (sessions, channel state, schedule state); point it at a mounted\n" +
243
+ " volume so a redeploy that replaces the directory never wipes it\n" +
244
+ " secrets: FASTAGENT_SECRETS_DIR > <agent dir>/.secrets — .env + auth.json\n" +
221
245
  " sessions: --sessions-dir > FASTAGENT_SESSIONS_DIR > <state>/sessions\n" +
222
- " auth: --auth-path > FASTAGENT_AUTH_PATH > <state>/auth.json\n" +
223
- " (project-level; point it at ~/.fastagent/auth.json to share one\n" +
224
- " credential across projects)",
246
+ " auth: --auth-path > FASTAGENT_AUTH_PATH > <secrets>/auth.json\n" +
247
+ " (project-level; point it at ~/.fastagent/.secrets/auth.json to\n" +
248
+ " share one credential across projects)",
225
249
  run: async (args, f) => (await import("./commands/start.js")).runStart(args[0], {
226
250
  port: f.port,
251
+ bind: f.bind,
227
252
  model: f.model,
228
253
  sessionsDir: f.sessionsDir,
229
254
  authPath: f.authPath,
@@ -286,7 +311,7 @@ const add = {
286
311
  "message pump, and an optional route() policy."),
287
312
  channelSub("slack", "scaffold the Slack Events API channel (files, threads, context, live preview)", "Choose group visibility, scaffold channels/slack.ts plus slack-send.ts, create a single-workspace " +
288
313
  "internal Slack app from a manifest, and install it through OAuth. The channel provides signed " +
289
- "Events API ingress, durable turns, files, managed threads, context, and an edited live preview.", "Automated onboarding requires Slack App Configuration access + refresh tokens and a temporary " +
314
+ "Events API ingress, durable turns, files, threads, context, and an edited live preview.", "Automated onboarding requires Slack App Configuration access + refresh tokens and a temporary " +
290
315
  "cloudflared tunnel. They stay in owner-readable local state and are never deployed; --no-onboard " +
291
316
  "keeps the explicit manual/scaffold-only path."),
292
317
  channelSub("feishu", "scaffold the Feishu channel AND create/configure the platform app", "Choose WebSocket or webhook, scaffold channels/feishu.ts, and create/configure the Feishu app " +
@@ -324,19 +349,22 @@ const add = {
324
349
  };
325
350
  const deploy = {
326
351
  name: "deploy",
327
- summary: "generate deploy artifacts + a runbook for docker, fly, or railway (--run drives it)",
352
+ summary: "generate deploy artifacts + a runbook for docker, fly, railway, or agentcore (--run drives it)",
328
353
  description: "Generate Dockerfile/.dockerignore plus the target config and print an ordered runbook. " +
329
354
  "docker: fastagent.compose.yml, loopback port, persistent state volume. fly: fly.toml " +
330
355
  "(autostop=suspend, state→volume). railway: railway.json (healthcheck /health); its " +
331
- "volume/variables/App-Sleeping are dashboard/CLI steps the runbook states. Durable ingress " +
332
- "remains operator-owned.",
333
- args: [{ name: "<host>", description: "deploy target", choices: ["docker", "fly", "railway"] }, DIR_ARG],
356
+ "volume/variables/App-Sleeping are dashboard/CLI steps the runbook states. agentcore: one " +
357
+ "CloudFormation stack (AWS Bedrock AgentCore Runtime + forwarder Lambda for webhooks + " +
358
+ "EventBridge rules for schedules; linux/arm64 image built locally). Durable ingress " +
359
+ "remains operator-owned (agentcore's forwarder URL is the exception — the stack owns it).",
360
+ args: [{ name: "<host>", description: "deploy target", choices: ["docker", "fly", "railway", "agentcore"] }, DIR_ARG],
334
361
  flags: [
335
362
  {
336
363
  flags: "--run",
337
364
  description: "drive the target CLI to completion. Docker runs `docker compose up -d --build`; with a tunnel " +
338
365
  "service, reads its URL and registers webhooks. Fly/Railway provision app/service + volume + " +
339
- "secrets + deploy + webhook setup. Carries your local credential (env key or OAuth auth.json). " +
366
+ "secrets + deploy + webhook setup. AgentCore builds/pushes the arm64 image and deploys the " +
367
+ "stack (aws + docker CLIs). Carries your local credential (env key or OAuth auth.json). " +
340
368
  "Stops at a gate (missing CLI/daemon/login/secret) with one actionable line. Without it: prints " +
341
369
  "the runbook",
342
370
  },
@@ -367,6 +395,7 @@ const deploy = {
367
395
  { cmd: "fastagent deploy fly --run", note: "provision + deploy + webhooks" },
368
396
  { cmd: "fastagent deploy docker --tunnel --run", note: "Compose + a public URL" },
369
397
  { cmd: "fastagent deploy railway", note: "print the runbook only" },
398
+ { cmd: "fastagent deploy agentcore --run", note: "arm64 image + stack + webhooks" },
370
399
  ],
371
400
  notes: "Definition-read-only: the only writes are generated artifacts (never clobbered without " +
372
401
  "--force). A routine redeploy of an already-provisioned agent is just the host's own command " +
@@ -427,10 +456,11 @@ const schedule = {
427
456
  const login = {
428
457
  name: "login",
429
458
  summary: "authenticate a model provider (subscription/OAuth or API key)",
430
- description: "Authenticate a model provider into the project-level <state root>/auth.json default " +
431
- "<cwd>/.fastagent/auth.json (run from $HOME for the global ~/.fastagent/auth.json): pick a method " +
432
- "(subscription/OAuth or API key), then a provider that offers it (configured status shown). " +
433
- "[provider] takes the method from what that provider supports, asked only when both.",
459
+ description: "Authenticate a model provider into the project-level <agent dir>/.secrets/auth.json (outside an " +
460
+ "agent it writes the global ~/.fastagent/.secrets/auth.json, and says so): pick a method " +
461
+ "(subscription/OAuth or API " +
462
+ "key), then a provider that offers it (configured status shown). [provider] takes the method from " +
463
+ "what that provider supports, asked only when both.",
434
464
  args: [{ name: "[provider]", description: "provider id (skip the provider menu)" }],
435
465
  flags: [AUTH_PATH, NO_INPUT],
436
466
  examples: [{ cmd: "fastagent login" }, { cmd: "fastagent login openai" }],