@fastagent-sh/fastagent 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/README.md +3 -3
  2. package/dist/agent.d.ts +20 -0
  3. package/dist/agent.js +9 -0
  4. package/dist/channels/context-buffer.d.ts +30 -0
  5. package/dist/channels/context-buffer.js +98 -0
  6. package/dist/channels/control.d.ts +28 -0
  7. package/dist/channels/control.js +214 -0
  8. package/dist/channels/feishu/card.js +1 -1
  9. package/dist/channels/feishu/context-buffer.d.ts +8 -11
  10. package/dist/channels/feishu/context-buffer.js +6 -67
  11. package/dist/channels/feishu/feishu-api.d.ts +11 -3
  12. package/dist/channels/feishu/feishu-api.js +20 -2
  13. package/dist/channels/feishu/feishu.d.ts +28 -16
  14. package/dist/channels/feishu/feishu.js +210 -188
  15. package/dist/channels/feishu/invoke-turn.d.ts +7 -20
  16. package/dist/channels/feishu/invoke-turn.js +10 -62
  17. package/dist/channels/feishu/model.d.ts +2 -1
  18. package/dist/channels/feishu/normalize.d.ts +2 -1
  19. package/dist/channels/feishu/owned-threads.d.ts +2 -6
  20. package/dist/channels/feishu/parse.d.ts +1 -1
  21. package/dist/channels/feishu/preview.d.ts +4 -7
  22. package/dist/channels/feishu/preview.js +24 -140
  23. package/dist/channels/feishu/register-app.d.ts +2 -1
  24. package/dist/channels/feishu/register-webhook.d.ts +2 -1
  25. package/dist/channels/feishu/setup-mode.d.ts +8 -0
  26. package/dist/channels/feishu/setup-mode.js +2 -0
  27. package/dist/channels/feishu/ws-ingress.d.ts +28 -0
  28. package/dist/channels/feishu/ws-ingress.js +136 -0
  29. package/dist/channels/github/github.js +8 -6
  30. package/dist/channels/http.d.ts +14 -0
  31. package/dist/channels/http.js +35 -2
  32. package/dist/channels/invoke-turn-kit.d.ts +65 -0
  33. package/dist/channels/invoke-turn-kit.js +87 -0
  34. package/dist/channels/lark/lark.d.ts +4 -2
  35. package/dist/channels/lark/lark.js +4 -1
  36. package/dist/channels/lark/onboard.d.ts +8 -4
  37. package/dist/channels/lark/onboard.js +8 -0
  38. package/dist/channels/preview-kit.d.ts +109 -0
  39. package/dist/channels/preview-kit.js +183 -0
  40. package/dist/channels/seen.d.ts +5 -0
  41. package/dist/channels/seen.js +35 -0
  42. package/dist/channels/slack/bot-auth.d.ts +15 -0
  43. package/dist/channels/slack/bot-auth.js +146 -0
  44. package/dist/channels/slack/config-api.d.ts +60 -0
  45. package/dist/channels/slack/config-api.js +149 -0
  46. package/dist/channels/slack/context-buffer.d.ts +24 -0
  47. package/dist/channels/slack/context-buffer.js +37 -0
  48. package/dist/channels/slack/invoke-turn.d.ts +19 -0
  49. package/dist/channels/slack/invoke-turn.js +63 -0
  50. package/dist/channels/slack/manifest.d.ts +49 -0
  51. package/dist/channels/slack/manifest.js +69 -0
  52. package/dist/channels/slack/model.d.ts +67 -0
  53. package/dist/channels/slack/model.js +2 -0
  54. package/dist/channels/slack/onboard.d.ts +41 -0
  55. package/dist/channels/slack/onboard.js +120 -0
  56. package/dist/channels/slack/onboarding-state.d.ts +31 -0
  57. package/dist/channels/slack/onboarding-state.js +69 -0
  58. package/dist/channels/slack/owned-threads.d.ts +6 -0
  59. package/dist/channels/slack/owned-threads.js +43 -0
  60. package/dist/channels/slack/parse.d.ts +23 -0
  61. package/dist/channels/slack/parse.js +81 -0
  62. package/dist/channels/slack/preview.d.ts +24 -0
  63. package/dist/channels/slack/preview.js +359 -0
  64. package/dist/channels/slack/reaction.d.ts +24 -0
  65. package/dist/channels/slack/reaction.js +62 -0
  66. package/dist/channels/slack/register-webhook.d.ts +10 -0
  67. package/dist/channels/slack/register-webhook.js +49 -0
  68. package/dist/channels/slack/scaffold/channel.ts +33 -0
  69. package/dist/channels/slack/scaffold/slack-send.ts +171 -0
  70. package/dist/channels/slack/setup-server.d.ts +17 -0
  71. package/dist/channels/slack/setup-server.js +103 -0
  72. package/dist/channels/slack/slack-api.d.ts +77 -0
  73. package/dist/channels/slack/slack-api.js +415 -0
  74. package/dist/channels/slack/slack.d.ts +58 -0
  75. package/dist/channels/slack/slack.js +451 -0
  76. package/dist/channels/slack/welcomed.d.ts +5 -0
  77. package/dist/channels/slack/welcomed.js +32 -0
  78. package/dist/channels/state.js +3 -3
  79. package/dist/channels/stop-command.d.ts +6 -0
  80. package/dist/channels/stop-command.js +36 -0
  81. package/dist/channels/tasks.d.ts +13 -0
  82. package/dist/channels/tasks.js +10 -0
  83. package/dist/channels/telegram/context-buffer.d.ts +8 -17
  84. package/dist/channels/telegram/context-buffer.js +6 -85
  85. package/dist/channels/telegram/invoke-turn.d.ts +5 -22
  86. package/dist/channels/telegram/invoke-turn.js +11 -58
  87. package/dist/channels/telegram/preview.d.ts +4 -7
  88. package/dist/channels/telegram/preview.js +24 -142
  89. package/dist/channels/telegram/telegram.js +23 -9
  90. package/dist/channels/{feishu/text.d.ts → text.d.ts} +1 -1
  91. package/dist/channels/{feishu/text.js → text.js} +1 -1
  92. package/dist/channels/turn-queue.js +1 -1
  93. package/dist/channels/turn-store.d.ts +1 -1
  94. package/dist/channels/turn-store.js +2 -3
  95. package/dist/cli/add-feishu.d.ts +27 -0
  96. package/dist/{cli-add-feishu.js → cli/add-feishu.js} +167 -44
  97. package/dist/cli/add-slack.d.ts +10 -0
  98. package/dist/cli/add-slack.js +204 -0
  99. package/dist/{cli-auth.d.ts → cli/auth-view.d.ts} +1 -1
  100. package/dist/{cli-auth.js → cli/auth-view.js} +1 -1
  101. package/dist/cli/commands/add.d.ts +4 -0
  102. package/dist/cli/commands/add.js +152 -20
  103. package/dist/cli/commands/attach.d.ts +82 -0
  104. package/dist/cli/commands/attach.js +559 -0
  105. package/dist/cli/commands/chat.d.ts +1 -0
  106. package/dist/cli/commands/chat.js +6 -1
  107. package/dist/cli/commands/deploy.d.ts +2 -0
  108. package/dist/cli/commands/deploy.js +78 -22
  109. package/dist/cli/commands/dev.js +11 -5
  110. package/dist/cli/commands/fire.js +3 -3
  111. package/dist/cli/commands/info.js +2 -2
  112. package/dist/cli/commands/invoke.js +2 -3
  113. package/dist/cli/commands/login.js +14 -25
  114. package/dist/cli/commands/models.js +1 -1
  115. package/dist/cli/commands/start.js +15 -8
  116. package/dist/cli/commands/tool.js +2 -1
  117. package/dist/cli/fail.d.ts +0 -2
  118. package/dist/cli/fail.js +1 -1
  119. package/dist/{invoke-stream.d.ts → cli/invoke-stream.d.ts} +1 -1
  120. package/dist/{invoke-stream.js → cli/invoke-stream.js} +4 -0
  121. package/dist/cli/kernel.d.ts +3 -2
  122. package/dist/cli/models-view.d.ts +21 -0
  123. package/dist/cli/models-view.js +66 -0
  124. package/dist/cli/program.js +79 -21
  125. package/dist/cli/serve.d.ts +38 -18
  126. package/dist/cli/serve.js +197 -39
  127. package/dist/cli/shared.d.ts +26 -6
  128. package/dist/cli/shared.js +163 -33
  129. package/dist/collect.d.ts +14 -3
  130. package/dist/collect.js +24 -0
  131. package/dist/core.d.ts +3 -1
  132. package/dist/core.js +2 -0
  133. package/dist/deploy/docker/plan.d.ts +2 -2
  134. package/dist/deploy/docker/plan.js +8 -6
  135. package/dist/deploy/fly/plan.d.ts +3 -1
  136. package/dist/deploy/fly/plan.js +12 -7
  137. package/dist/deploy/fly/run.d.ts +5 -4
  138. package/dist/deploy/fly/run.js +16 -5
  139. package/dist/deploy/preflight.d.ts +10 -4
  140. package/dist/deploy/preflight.js +53 -9
  141. package/dist/deploy/railway/plan.d.ts +3 -1
  142. package/dist/deploy/railway/plan.js +12 -4
  143. package/dist/deploy/railway/run.d.ts +5 -4
  144. package/dist/deploy/railway/run.js +15 -5
  145. package/dist/deploy/runner.d.ts +2 -1
  146. package/dist/deploy/secrets.d.ts +2 -1
  147. package/dist/deploy/secrets.js +23 -3
  148. package/dist/dev-supervisor.d.ts +0 -2
  149. package/dist/dev-supervisor.js +7 -3
  150. package/dist/engines/pi/channel.d.ts +22 -16
  151. package/dist/engines/pi/channel.js +90 -60
  152. package/dist/engines/pi/chat.d.ts +4 -16
  153. package/dist/engines/pi/chat.js +8 -261
  154. package/dist/engines/pi/config.d.ts +14 -9
  155. package/dist/engines/pi/config.js +33 -18
  156. package/dist/engines/pi/create.d.ts +22 -2
  157. package/dist/engines/pi/create.js +20 -14
  158. package/dist/engines/pi/harness.d.ts +49 -0
  159. package/dist/engines/pi/harness.js +90 -2
  160. package/dist/engines/pi/invoke.d.ts +55 -2
  161. package/dist/engines/pi/invoke.js +304 -19
  162. package/dist/engines/pi/login.d.ts +11 -0
  163. package/dist/engines/pi/login.js +16 -4
  164. package/dist/engines/pi/models.d.ts +56 -10
  165. package/dist/engines/pi/models.js +61 -23
  166. package/dist/engines/pi/session-builder.d.ts +16 -0
  167. package/dist/engines/pi/session-builder.js +308 -0
  168. package/dist/engines/pi/session-control.d.ts +50 -0
  169. package/dist/engines/pi/session-control.js +604 -0
  170. package/dist/engines/pi/sessions.d.ts +17 -2
  171. package/dist/engines/pi/sessions.js +9 -0
  172. package/dist/engines/pi/tool-context.d.ts +18 -11
  173. package/dist/engines/pi/tool-context.js +3 -9
  174. package/dist/engines/pi/tool.d.ts +6 -8
  175. package/dist/engines/pi/tool.js +6 -1
  176. package/dist/engines/pi/wake-tool.d.ts +0 -3
  177. package/dist/engines/pi/wake-tool.js +9 -7
  178. package/dist/engines/pi/workspace.d.ts +52 -0
  179. package/dist/engines/pi/workspace.js +72 -15
  180. package/dist/feishu.d.ts +1 -1
  181. package/dist/feishu.js +1 -1
  182. package/dist/host/node.d.ts +23 -6
  183. package/dist/host/node.js +5 -4
  184. package/dist/index.d.ts +1 -0
  185. package/dist/index.js +1 -0
  186. package/dist/lark.d.ts +1 -1
  187. package/dist/lark.js +1 -1
  188. package/dist/observe.js +3 -0
  189. package/dist/pi.d.ts +5 -4
  190. package/dist/pi.js +2 -1
  191. package/dist/scaffold/add-channel.d.ts +19 -6
  192. package/dist/scaffold/add-channel.js +126 -17
  193. package/dist/scaffold/templates/fastagent.config.mjs +4 -3
  194. package/dist/schedule/wakeups.d.ts +0 -3
  195. package/dist/schedule/wakeups.js +1 -1
  196. package/dist/session-remote.d.ts +53 -0
  197. package/dist/session-remote.js +336 -0
  198. package/dist/session.d.ts +265 -0
  199. package/dist/session.js +37 -0
  200. package/dist/slack.d.ts +2 -0
  201. package/dist/slack.js +2 -0
  202. package/dist/tunnel.d.ts +7 -4
  203. package/dist/tunnel.js +21 -10
  204. package/package.json +19 -7
  205. package/dist/channels/feishu/seen.d.ts +0 -5
  206. package/dist/channels/feishu/seen.js +0 -47
  207. package/dist/cli-add-feishu.d.ts +0 -8
  208. package/dist/cli-models.d.ts +0 -11
  209. package/dist/cli-models.js +0 -20
@@ -1,19 +1,27 @@
1
1
  /**
2
2
  * `fastagent add <channel>|skill` — scaffold channel glue (`channels/<kind>.ts`) or vendor an Agent
3
- * Skills skill. feishu/lark additionally CREATE OR RESUME the platform app (cli-add-feishu.ts).
3
+ * Skills skill. slack/feishu/lark additionally CREATE OR RESUME the platform app.
4
4
  */
5
5
  import { randomBytes } from "node:crypto";
6
+ import { readFile } from "node:fs/promises";
6
7
  import { join, relative, resolve } from "node:path";
7
- import { onboardFeishuCloudApp } from "../../cli-add-feishu.js";
8
- import { loadConfig, resolveAgentDir } from "../../engines/pi/config.js";
8
+ import { isCancel, select } from "@clack/prompts";
9
+ import { onboardFeishuCloudApp } from "../add-feishu.js";
10
+ import { loadDotEnv } from "../../env.js";
11
+ import { loadConfig, resolveAgentDir, resolveStateRoot } from "../../engines/pi/config.js";
9
12
  import { detectRuntime, readPackageJson } from "../../runtime.js";
10
13
  import { appendChannelDotEnv, appendChannelEnv, assertChannelReady, channelExists, channelSetup, scaffoldChannel, } from "../../scaffold/add-channel.js";
14
+ import { exists } from "../../scaffold/init.js";
11
15
  import { vendorSkill } from "../../scaffold/vendor-skill.js";
12
16
  import { loadRootIgnore } from "../../workspace.js";
13
17
  import { failStartup, failUsage } from "../fail.js";
14
18
  /** `fastagent add <kind> [dir]`: scaffold `channels/<kind>.ts` — the adapter import plus a starter `on()`. */
15
19
  export async function runAddChannel(channelKind, dirArg, opts) {
16
20
  const target = resolve(dirArg);
21
+ if (opts.replaceConfig && opts.onboard === false) {
22
+ failUsage("--replace-config replaces onboarding credentials; it cannot be combined with --no-onboard");
23
+ }
24
+ loadDotEnv(target); // onboarding state follows the same FASTAGENT_STATE_DIR as serving/deploy
17
25
  // App creation is not a flag — it is what `add feishu` IS (the scan-to-create flow is the default
18
26
  // and only path there). The retired --create-app spelling gets a pointer, not silence.
19
27
  if (opts.createApp) {
@@ -32,22 +40,30 @@ export async function runAddChannel(channelKind, dirArg, opts) {
32
40
  // hygiene stay at the run root, where .env is actually read.
33
41
  const { config: addConfig } = await loadConfig(target).catch(failStartup);
34
42
  const channelHome = resolveAgentDir(target, addConfig);
35
- // Preconditions before the write, so a refusal is side-effect-free. feishu/lark are exceptions:
43
+ // Preconditions before the write, so a refusal is side-effect-free. slack/feishu/lark are exceptions:
36
44
  // their add is scaffold + ONBOARD THE APP, so an existing scaffold skips the write and continues (a
37
- // failed or cancelled scan/paste flow must be re-runnable without hand-deleting glue); never touch it.
45
+ // failed/cancelled app or OAuth flow must be re-runnable without hand-deleting authored glue).
38
46
  const file = join(channelHome, "channels", `${channelKind}.ts`);
39
- if (await channelExists(channelHome, channelKind).catch(failStartup)) {
40
- if (channelKind !== "feishu" && channelKind !== "lark") {
47
+ const slackToolFile = join(channelHome, "tools", "slack-send.ts");
48
+ const slackToolExisted = channelKind === "slack" ? await exists(slackToolFile) : false;
49
+ const existsAlready = await channelExists(channelHome, channelKind).catch(failStartup);
50
+ const ingress = await resolveIngress(channelKind, file, existsAlready, opts.ingress);
51
+ const groupBehavior = await resolveGroupBehavior(channelKind, opts.groupBehavior);
52
+ if (existsAlready) {
53
+ if (channelKind !== "slack" && channelKind !== "feishu" && channelKind !== "lark") {
41
54
  failStartup(new Error(`${relative(target, file)} already exists — edit it, or remove it to re-scaffold`));
42
55
  }
43
56
  console.error(`[fastagent] ${relative(target, file)} already exists — keeping it`);
44
57
  }
45
58
  else {
46
59
  await assertChannelReady(channelHome).catch(failStartup);
47
- await scaffoldChannel(channelHome, channelKind).catch(failStartup);
60
+ await scaffoldChannel(channelHome, channelKind, { ingress, groupBehavior: groupBehavior.behavior }).catch(failStartup);
48
61
  console.error(`[fastagent] created ${relative(target, file)}`);
62
+ if (channelKind === "slack") {
63
+ console.error(`[fastagent] ${slackToolExisted ? "kept existing" : "created"} ${relative(target, slackToolFile)}`);
64
+ }
49
65
  }
50
- if (await appendChannelEnv(target, channelKind).catch(failStartup)) {
66
+ if (await appendChannelEnv(target, channelKind, ingress).catch(failStartup)) {
51
67
  console.error(`[fastagent] added ${channelKind} env vars to .env.example`);
52
68
  }
53
69
  // Secret hygiene: a channel's GENERATED secret (a random string the user contributes nothing to) is
@@ -58,20 +74,40 @@ export async function runAddChannel(channelKind, dirArg, opts) {
58
74
  if (!envIgnored) {
59
75
  console.error(`[fastagent] warn: .env is not gitignored — a deploy that copies the directory would ship a secret placed there; add .env to .gitignore/.fastagentignore, or use a real env var`);
60
76
  }
61
- // `add feishu`/`add lark` = scaffold + CREATE OR RESUME the app (cli-add-feishu.ts): feishu persists
62
- // its irreversible App ID/Secret boundary internally; lark returns guided credentials for the
63
- // generic .env write below.
77
+ // Stateful app onboarding is re-runnable after the scaffold boundary. Slack's internal-app path
78
+ // persists its manifest/OAuth recovery state separately and writes runtime secrets directly.
64
79
  let created;
65
- if (channelKind === "feishu" || channelKind === "lark") {
66
- created = await onboardFeishuCloudApp(target, channelKind, envIgnored).catch(failStartup);
80
+ if (channelKind === "slack" && opts.onboard !== false) {
81
+ const { onboardSlackInternalApp } = await import("../add-slack.js");
82
+ created = await onboardSlackInternalApp({
83
+ target,
84
+ stateRoot: resolveStateRoot(target),
85
+ envIgnored,
86
+ groupBehavior,
87
+ replaceConfig: opts.replaceConfig,
88
+ })
89
+ .then(() => undefined)
90
+ .catch(failStartup);
67
91
  }
68
- const { env, steps } = channelSetup(channelKind);
92
+ else if (channelKind === "feishu" || channelKind === "lark") {
93
+ created = await onboardFeishuCloudApp(target, channelKind, envIgnored, ingress, groupBehavior).catch(failStartup);
94
+ }
95
+ const setup = channelSetup(channelKind, ingress, groupBehavior.behavior);
96
+ const env = setup.env;
97
+ const steps = channelKind === "slack" && opts.onboard !== false
98
+ ? [
99
+ "Slack internal app created/configured/installed through OAuth; runtime credentials are in .env",
100
+ "run fastagent dev --tunnel to replace the temporary Events API URL automatically",
101
+ "invite the app to every channel it should read",
102
+ "the agent can send messages or files by calling the scaffolded {tools}/slack-send.ts tool",
103
+ ]
104
+ : setup.steps;
69
105
  const generated = Object.fromEntries(env.filter((e) => e.generate).map((e) => [e.name, randomBytes(24).toString("hex")]));
70
106
  // Kind-neutral: every channel's generated secrets get the same treatment (github's webhook secret is
71
107
  // the same class of value as telegram's); guided Lark credentials ride the same write as overwrites.
72
- // Feishu's irreversible credentials were already staged inside cli-add-feishu.ts before bootstrap.
108
+ // Feishu's irreversible credentials were already staged inside add-feishu.ts before bootstrap.
73
109
  const dotEnv = envIgnored
74
- ? await appendChannelDotEnv(target, channelKind, { ...generated, ...created }, Object.keys(created ?? {})).catch(failStartup)
110
+ ? await appendChannelDotEnv(target, channelKind, { ...generated, ...created }, Object.keys(created ?? {}), ingress).catch(failStartup)
75
111
  : undefined;
76
112
  if (dotEnv && dotEnv.written.length > 0) {
77
113
  console.error(`[fastagent] wrote ${dotEnv.written.join(", ")} to .env`);
@@ -100,13 +136,109 @@ export async function runAddChannel(channelKind, dirArg, opts) {
100
136
  for (const s of steps) {
101
137
  console.error(` ${s.replace("{channel}", relative(target, file)).replace("{tools}", `${kitPrefix}tools`)}`);
102
138
  }
103
- if (channelKind !== "lark") {
139
+ if (ingress === "websocket") {
140
+ console.error(` fastagent dev # no public URL or tunnel required`);
141
+ }
142
+ else if (channelKind === "slack") {
143
+ console.error(` fastagent dev --tunnel # serve locally; ${opts.onboard === false ? "print the Request URL for manual Slack setup" : "auto-update the onboarded Slack Request URL"}`);
144
+ }
145
+ else if (channelKind === "github") {
146
+ console.error(` fastagent dev --tunnel # serve locally + print the URL for manual GitHub webhook setup`);
147
+ }
148
+ else if (channelKind !== "lark") {
104
149
  console.error(` fastagent dev --tunnel # serve locally + a public URL, auto-registering the webhook`);
105
150
  }
106
- // The app-creation flow leaves keep-alive sockets behind (platform API fetches, the throwaway tunnel's
107
- // health probes) that would hold the event loop open for a while the work is done, exit crisply.
151
+ // App-creation flows leave platform/tunnel sockets behind that would otherwise hold the one-shot
152
+ // scaffold command open after all durable boundaries have completed — exit crisply.
108
153
  process.exit(0);
109
154
  }
155
+ async function resolveIngress(kind, file, existsAlready, raw) {
156
+ if (raw !== undefined && raw !== "webhook" && raw !== "websocket") {
157
+ failUsage(`--ingress must be "webhook" or "websocket", got "${raw}"`);
158
+ }
159
+ const requested = raw;
160
+ if (kind !== "feishu" && kind !== "lark")
161
+ return "webhook";
162
+ if (existsAlready) {
163
+ const source = await readFile(file, "utf8").catch(failStartup);
164
+ const factory = source.match(/\b(?:feishu|lark)(WebSocket)?Channel\s*\(/);
165
+ const existing = factory
166
+ ? factory[1] === "WebSocket"
167
+ ? "websocket"
168
+ : "webhook"
169
+ : undefined;
170
+ if (!existing) {
171
+ if (!requested) {
172
+ failUsage(`${file} uses an unrecognized channel factory — re-run with --ingress webhook|websocket to confirm its mode`);
173
+ }
174
+ return requested;
175
+ }
176
+ if (requested && requested !== existing) {
177
+ failStartup(new Error(`${file} already selects ${existing} delivery — changing mode is a migration; edit the factory and platform subscription together`));
178
+ }
179
+ return existing;
180
+ }
181
+ if (requested)
182
+ return requested;
183
+ if (!(process.stdin.isTTY && process.stdout.isTTY)) {
184
+ console.error(`[fastagent] no interactive terminal — defaulting ${kind} ingress to webhook (use --ingress websocket)`);
185
+ return "webhook";
186
+ }
187
+ const answer = await select({
188
+ message: `How should ${kind === "feishu" ? "Feishu" : "Lark"} deliver events?`,
189
+ options: [
190
+ {
191
+ value: "websocket",
192
+ label: "WebSocket long connection",
193
+ hint: "no public URL; requires an always-on process",
194
+ },
195
+ {
196
+ value: "webhook",
197
+ label: "Webhook endpoint",
198
+ hint: "supports scale-to-zero; requires a public HTTPS URL",
199
+ },
200
+ ],
201
+ });
202
+ if (isCancel(answer))
203
+ failStartup(new Error(`${kind} onboarding cancelled`));
204
+ return answer;
205
+ }
206
+ async function resolveGroupBehavior(kind, raw) {
207
+ if (raw !== undefined && raw !== "context" && raw !== "mentions") {
208
+ failUsage(`--group-behavior must be "context" or "mentions", got "${raw}"`);
209
+ }
210
+ if (kind !== "feishu" && kind !== "lark" && kind !== "slack")
211
+ return { behavior: "context", explicit: false };
212
+ if (raw !== undefined)
213
+ return { behavior: raw, explicit: true };
214
+ const defaultBehavior = "context";
215
+ if (!(process.stdin.isTTY && process.stdout.isTTY)) {
216
+ console.error(`[fastagent] no interactive terminal — assuming ${kind} group behavior ${defaultBehavior}; pass --group-behavior explicitly to override`);
217
+ return { behavior: defaultBehavior, explicit: false };
218
+ }
219
+ const choices = [
220
+ {
221
+ value: "context",
222
+ label: "Context-aware groups (recommended)",
223
+ hint: kind === "slack"
224
+ ? "bare managed-thread replies + buffer; requires channel/group/mpim history scopes"
225
+ : "bare managed-thread replies + buffer; im:message.group_msg delivers all group messages",
226
+ },
227
+ {
228
+ value: "mentions",
229
+ label: "Mention-only (least privilege)",
230
+ hint: "only explicit @Agent messages; no group-wide message permission",
231
+ },
232
+ ];
233
+ const answer = await select({
234
+ message: "Choose group-chat behavior",
235
+ initialValue: defaultBehavior,
236
+ options: choices,
237
+ });
238
+ if (isCancel(answer))
239
+ failStartup(new Error(`${kind} onboarding cancelled`));
240
+ return { behavior: answer, explicit: true };
241
+ }
110
242
  /** `fastagent add skill <source> [dir]`: vendor an Agent Skills skill into <dir>/skills/<name>/. */
111
243
  export async function runAddSkill(source, dirArg, opts) {
112
244
  const target = resolve(dirArg);
@@ -0,0 +1,82 @@
1
+ import type { SessionControl } from "../../session.ts";
2
+ export interface AttachOptions {
3
+ /** Override the control endpoint (skip control.json discovery) — for a remote serve. */
4
+ url?: string;
5
+ token?: string;
6
+ }
7
+ export declare function runAttach(sessionArg: string, dirArg: string | undefined, opts: AttachOptions): Promise<void>;
8
+ /** One round's observed facts, gathered by the loop (IO) and judged by {@link decideRound} (pure). */
9
+ export type RoundOutcome = {
10
+ type: "progress";
11
+ }
12
+ /** Clean end that delivered nothing — indistinguishable from a half-dead proxy closing every stream. */
13
+ | {
14
+ type: "empty";
15
+ } | {
16
+ type: "error";
17
+ error: unknown;
18
+ isAuth: boolean;
19
+ /** discover(dir) compared against the current endpoint; remote endpoints report "unavailable". */
20
+ discovery: "unchanged" | "changed" | "unavailable";
21
+ /** The freshly discovered credentials when {@link discovery} is "changed". */
22
+ fresh?: {
23
+ url: string;
24
+ token: string;
25
+ };
26
+ };
27
+ export type RoundDecision = {
28
+ kind: "reset";
29
+ } | {
30
+ kind: "exit";
31
+ message: string;
32
+ } | {
33
+ kind: "try-reattach";
34
+ fresh: {
35
+ url: string;
36
+ token: string;
37
+ };
38
+ } | {
39
+ kind: "retry";
40
+ warn: string;
41
+ };
42
+ /**
43
+ * The reconnect policy for BOTH phases (`startup` = connectWithGrace, `steady` = the round loop),
44
+ * pure and testable: every exit diagnosis and budget claim lives here. `downMs` is wall-clock time
45
+ * since the phase's anchor (first connect attempt / first non-progress round). The phases differ
46
+ * on priors, not principle: startup has never succeeded (short budget; a remote non-auth error
47
+ * exits at once), steady-state had a working attach (longer budgets); the local-401-unchanged
48
+ * diagnosis and reattach-on-changed-credentials apply identically to both.
49
+ */
50
+ export declare function decideRound(outcome: RoundOutcome, ctx: {
51
+ discovered: boolean;
52
+ downMs: number;
53
+ phase?: "startup" | "steady";
54
+ }): RoundDecision;
55
+ /** What one ROUND prints through (streamed deltas included), so tests can observe every path a
56
+ * round writes. Round output only: stdin-side acceptance/rejection lines print directly — they
57
+ * are immediate feedback to a user action and may interleave with a replay block. Timing knobs
58
+ * travel as their own parameter. */
59
+ export interface AttachIo {
60
+ println: (line: string) => void;
61
+ /** Raw chunk, no newline — the streamed message_delta path. */
62
+ write: (chunk: string) => void;
63
+ warn: (line: string) => void;
64
+ }
65
+ /**
66
+ * ONE attach round: subscribe → backfill (render the durable record since `cursor`) → drain live
67
+ * until the stream drops. Returns the advanced cursor. Subscribing first + the server's eager
68
+ * registration (subscribed before response headers) covers the cursor→subscription window in the
69
+ * normal case; `settleMs` is a HEURISTIC — on a very slow link an event can still land between the
70
+ * backfill and the subscription taking effect, surfacing only at the next round's replay. Live
71
+ * events carry no entry ids, so the cursor advances only on backfill; a replay may overlap what
72
+ * was already seen live — labeled, not silently dropped. A 401 (stale token after a serve restart)
73
+ * is thrown to the caller: unrecoverable here, never retried silently.
74
+ */
75
+ export declare function attachRound(control: SessionControl, session: string, cursor: string | undefined, io: AttachIo,
76
+ /** The subscribe→sync settle heuristic (see the round comment). Tests shrink it. */
77
+ settleMs?: number): Promise<{
78
+ cursor: string | undefined;
79
+ sawProgress: boolean;
80
+ }>;
81
+ /** The cursor a failed round reached, if it recorded one. */
82
+ export declare function roundCursor(error: unknown): string | undefined;