@fastagent-sh/fastagent 0.12.1 → 0.14.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 (151) hide show
  1. package/README.md +6 -4
  2. package/dist/channels/feishu/bootstrap-token.d.ts +42 -0
  3. package/dist/channels/feishu/bootstrap-token.js +94 -0
  4. package/dist/channels/feishu/card.d.ts +32 -0
  5. package/dist/channels/feishu/card.js +66 -0
  6. package/dist/channels/feishu/cloud.d.ts +17 -0
  7. package/dist/channels/feishu/cloud.js +19 -0
  8. package/dist/channels/feishu/context-buffer.d.ts +46 -0
  9. package/dist/channels/feishu/context-buffer.js +133 -0
  10. package/dist/channels/feishu/crypto.d.ts +15 -0
  11. package/dist/channels/feishu/crypto.js +43 -0
  12. package/dist/channels/feishu/feishu-api.d.ts +108 -0
  13. package/dist/channels/feishu/feishu-api.js +325 -0
  14. package/dist/channels/feishu/feishu.d.ts +46 -0
  15. package/dist/channels/feishu/feishu.js +472 -0
  16. package/dist/channels/feishu/invoke-turn.d.ts +65 -0
  17. package/dist/channels/feishu/invoke-turn.js +157 -0
  18. package/dist/channels/feishu/model.d.ts +97 -0
  19. package/dist/channels/feishu/model.js +9 -0
  20. package/dist/channels/feishu/normalize.d.ts +22 -0
  21. package/dist/channels/feishu/normalize.js +132 -0
  22. package/dist/channels/feishu/owned-threads.d.ts +11 -0
  23. package/dist/channels/feishu/owned-threads.js +47 -0
  24. package/dist/channels/feishu/parse.d.ts +43 -0
  25. package/dist/channels/feishu/parse.js +65 -0
  26. package/dist/channels/feishu/preview.d.ts +36 -0
  27. package/dist/channels/feishu/preview.js +387 -0
  28. package/dist/channels/feishu/register-app.d.ts +70 -0
  29. package/dist/channels/feishu/register-app.js +141 -0
  30. package/dist/channels/feishu/register-webhook.d.ts +22 -0
  31. package/dist/channels/feishu/register-webhook.js +106 -0
  32. package/dist/channels/feishu/scaffold/channel.ts +41 -0
  33. package/dist/channels/feishu/scaffold/feishu-send.ts +87 -0
  34. package/dist/channels/feishu/seen.d.ts +5 -0
  35. package/dist/channels/feishu/seen.js +47 -0
  36. package/dist/channels/feishu/text.d.ts +13 -0
  37. package/dist/channels/feishu/text.js +63 -0
  38. package/dist/channels/lark/lark.d.ts +15 -0
  39. package/dist/channels/lark/lark.js +10 -0
  40. package/dist/channels/lark/onboard.d.ts +39 -0
  41. package/dist/channels/lark/onboard.js +58 -0
  42. package/dist/channels/lark/scaffold/channel.ts +39 -0
  43. package/dist/channels/lark/scaffold/lark-send.ts +87 -0
  44. package/dist/channels/registration.d.ts +15 -0
  45. package/dist/channels/registration.js +1 -0
  46. package/dist/channels/{telegram/state.js → state.js} +6 -4
  47. package/dist/channels/telegram/context-buffer.js +1 -1
  48. package/dist/channels/telegram/register-webhook.d.ts +4 -1
  49. package/dist/channels/telegram/register-webhook.js +17 -26
  50. package/dist/channels/telegram/telegram.js +2 -2
  51. package/dist/channels/telegram/turn-store.d.ts +8 -21
  52. package/dist/channels/telegram/turn-store.js +11 -130
  53. package/dist/channels/{telegram/turn-queue.js → turn-queue.js} +3 -3
  54. package/dist/channels/turn-store.d.ts +42 -0
  55. package/dist/channels/turn-store.js +139 -0
  56. package/dist/channels/wait-health.d.ts +6 -0
  57. package/dist/channels/wait-health.js +27 -0
  58. package/dist/cli/commands/add.d.ts +9 -0
  59. package/dist/cli/commands/add.js +142 -0
  60. package/dist/cli/commands/chat.d.ts +3 -0
  61. package/dist/cli/commands/chat.js +16 -0
  62. package/dist/cli/commands/deploy.d.ts +13 -0
  63. package/dist/cli/commands/deploy.js +338 -0
  64. package/dist/cli/commands/dev.d.ts +11 -0
  65. package/dist/cli/commands/dev.js +76 -0
  66. package/dist/cli/commands/fire.d.ts +7 -0
  67. package/dist/cli/commands/fire.js +45 -0
  68. package/dist/cli/commands/info.d.ts +7 -0
  69. package/dist/cli/commands/info.js +108 -0
  70. package/dist/cli/commands/init.d.ts +8 -0
  71. package/dist/cli/commands/init.js +81 -0
  72. package/dist/cli/commands/invoke.d.ts +7 -0
  73. package/dist/cli/commands/invoke.js +29 -0
  74. package/dist/cli/commands/login.d.ts +6 -0
  75. package/dist/cli/commands/login.js +63 -0
  76. package/dist/cli/commands/models.d.ts +1 -0
  77. package/dist/cli/commands/models.js +15 -0
  78. package/dist/cli/commands/schedule.d.ts +12 -0
  79. package/dist/cli/commands/schedule.js +89 -0
  80. package/dist/cli/commands/start.d.ts +10 -0
  81. package/dist/cli/commands/start.js +90 -0
  82. package/dist/cli/commands/tool.d.ts +1 -0
  83. package/dist/cli/commands/tool.js +37 -0
  84. package/dist/cli/fail.d.ts +19 -0
  85. package/dist/cli/fail.js +32 -0
  86. package/dist/cli/kernel.d.ts +89 -0
  87. package/dist/cli/kernel.js +190 -0
  88. package/dist/cli/program.d.ts +11 -0
  89. package/dist/cli/program.js +421 -0
  90. package/dist/cli/serve.d.ts +28 -0
  91. package/dist/cli/serve.js +90 -0
  92. package/dist/cli/shared.d.ts +24 -0
  93. package/dist/cli/shared.js +116 -0
  94. package/dist/cli-add-feishu.d.ts +8 -0
  95. package/dist/cli-add-feishu.js +223 -0
  96. package/dist/cli.js +8 -1284
  97. package/dist/deploy/container.js +10 -6
  98. package/dist/deploy/docker/plan.d.ts +45 -0
  99. package/dist/deploy/docker/plan.js +139 -0
  100. package/dist/deploy/docker/run.d.ts +40 -0
  101. package/dist/deploy/docker/run.js +126 -0
  102. package/dist/deploy/fly/plan.d.ts +1 -1
  103. package/dist/deploy/fly/plan.js +15 -4
  104. package/dist/deploy/fly/run.d.ts +7 -4
  105. package/dist/deploy/fly/run.js +26 -5
  106. package/dist/deploy/preflight.js +4 -3
  107. package/dist/deploy/railway/plan.d.ts +1 -1
  108. package/dist/deploy/railway/plan.js +17 -5
  109. package/dist/deploy/railway/run.d.ts +6 -3
  110. package/dist/deploy/railway/run.js +26 -4
  111. package/dist/deploy/registration-gate.d.ts +20 -0
  112. package/dist/deploy/registration-gate.js +20 -0
  113. package/dist/deploy/runner.d.ts +4 -1
  114. package/dist/deploy/runner.js +1 -0
  115. package/dist/deploy/secrets.d.ts +10 -9
  116. package/dist/deploy/secrets.js +15 -14
  117. package/dist/dev-supervisor.js +2 -1
  118. package/dist/engines/pi/auth.js +160 -46
  119. package/dist/engines/pi/chat.js +80 -7
  120. package/dist/engines/pi/config.d.ts +12 -3
  121. package/dist/engines/pi/config.js +16 -1
  122. package/dist/engines/pi/create.d.ts +14 -6
  123. package/dist/engines/pi/create.js +52 -16
  124. package/dist/engines/pi/harness.d.ts +16 -1
  125. package/dist/engines/pi/harness.js +77 -1
  126. package/dist/engines/pi/invoke.d.ts +1 -1
  127. package/dist/engines/pi/invoke.js +37 -2
  128. package/dist/engines/pi/login.js +1 -1
  129. package/dist/engines/pi/search-tools.d.ts +10 -0
  130. package/dist/engines/pi/search-tools.js +138 -0
  131. package/dist/engines/pi/tool-context.d.ts +28 -0
  132. package/dist/engines/pi/tool-context.js +8 -0
  133. package/dist/engines/pi/tool.d.ts +32 -1
  134. package/dist/engines/pi/tool.js +42 -1
  135. package/dist/engines/pi/workspace.d.ts +4 -1
  136. package/dist/engines/pi/workspace.js +3 -1
  137. package/dist/feishu.d.ts +2 -0
  138. package/dist/feishu.js +2 -0
  139. package/dist/lark.d.ts +3 -0
  140. package/dist/lark.js +3 -0
  141. package/dist/open-url.d.ts +2 -0
  142. package/dist/open-url.js +6 -0
  143. package/dist/pi.d.ts +2 -1
  144. package/dist/scaffold/add-channel.d.ts +9 -5
  145. package/dist/scaffold/add-channel.js +75 -7
  146. package/dist/scaffold/templates/fastagent.config.mjs +1 -0
  147. package/dist/tunnel.d.ts +9 -6
  148. package/dist/tunnel.js +48 -31
  149. package/package.json +18 -4
  150. /package/dist/channels/{telegram/state.d.ts → state.d.ts} +0 -0
  151. /package/dist/channels/{telegram/turn-queue.d.ts → turn-queue.d.ts} +0 -0
@@ -0,0 +1,138 @@
1
+ /**
2
+ * The built-in `search_tools` loader — the discovery surface for deferred tools (defineTool
3
+ * `deferred: true`). A deferred tool's schema is not in the request and the model cannot see it; this
4
+ * loader is how it finds and activates one. Mounted automatically (withSearchTool) only when a
5
+ * deferred tool exists; a workspace tool named `search_tools` wins — the author owns the concept then
6
+ * (same rule as the wake pair).
7
+ */
8
+ import { z } from "zod";
9
+ import { log } from "../../log.js";
10
+ import { defineTool, isDeferredTool, stripDeferredMarker } from "./tool.js";
11
+ /** Mount the built-in loader iff any mounted tool is deferred and the author didn't define their own. */
12
+ export function withSearchTool(tools) {
13
+ if (!tools.some(isDeferredTool))
14
+ return tools;
15
+ const authored = tools.find((t) => t.name === "search_tools");
16
+ if (!authored)
17
+ return [...tools, makeSearchToolsTool()];
18
+ let fixed = authored;
19
+ if (isDeferredTool(fixed)) {
20
+ // A deferred LOADER is a contradiction — it is the only entry point to the deferred tools, so
21
+ // nothing could ever activate it (or, through it, them): every deferred tool would be silently
22
+ // unreachable. Ignore the marker and keep the loader active (fail visibly, keep the capability).
23
+ log.warn("[fastagent] search_tools is marked deferred — ignoring the marker: the loader must stay active, or no deferred tool could ever be activated");
24
+ fixed = stripDeferredMarker(fixed);
25
+ }
26
+ if (fixed.executionMode !== "sequential") {
27
+ // A non-sequential loader silently revives the parallel double-attribution (pi's diff around SDK
28
+ // tools in chat) — enforce the mode rather than hope the author read the docs; warn so they know.
29
+ log.warn('[fastagent] search_tools lacks executionMode: "sequential" — forcing it: parallel loader calls would misattribute activations');
30
+ fixed = { ...fixed, executionMode: "sequential" };
31
+ }
32
+ return fixed === authored ? tools : tools.map((t) => (t === authored ? fixed : t));
33
+ }
34
+ /** Activation cap per search: activation is additive, session-persisted, and has NO deactivate path —
35
+ * without a cap, one broad token ("get", "file") would permanently activate half the catalog and
36
+ * silently spend the entire deferral benefit for the rest of the conversation. Over the cap nothing
37
+ * activates; the model gets the candidates and narrows the query. */
38
+ const MAX_ACTIVATIONS_PER_SEARCH = 5;
39
+ /** Miss-path listing cap — same rationale as the activation cap: a typo query must not pour the whole
40
+ * catalog (the thing deferral keeps OUT of the context) back in as a tool result. */
41
+ const MAX_MISS_LISTING = 10;
42
+ /** Build the `search_tools` loader. Keyword search over the inactive tools' name+description.
43
+ *
44
+ * `executionMode: "sequential"` — pi turns any batch containing a sequential tool serial. Required for
45
+ * correct load-point attribution everywhere an OUTER active-set diff exists: pi wraps SDK customTools
46
+ * (the chat path) in a before/after diff, and two parallel loader calls would both snapshot the
47
+ * pre-activation set and get stamped with the same activation. Custom loader authors must set it too. */
48
+ export function makeSearchToolsTool() {
49
+ return defineTool({
50
+ name: "search_tools",
51
+ executionMode: "sequential",
52
+ description:
53
+ // First line short on purpose: the base prompt's tools list truncates at the first newline, and
54
+ // the discovery guidance below would otherwise flood it (and duplicate its deferred note).
55
+ "Discover and activate additional tools.\n" +
56
+ "Part of this agent's toolset is inactive until needed: search by keywords (e.g. what you are " +
57
+ "trying to do), and matching inactive tools are activated and become callable from that point on " +
58
+ "(if too many match, you get the candidates back — narrow the query, or query an exact tool " +
59
+ "name). ALWAYS search here before concluding a capability is missing.",
60
+ input: z.object({
61
+ query: z.string().min(1).describe("keywords describing the capability you need (e.g. 'weather forecast')"),
62
+ }),
63
+ async execute(input, ctx) {
64
+ if (!ctx.tools)
65
+ return "tool activation is unavailable outside a conversation turn.";
66
+ // Search the WHOLE registered catalog: the loader is the only discovery surface, and in a long
67
+ // conversation the model does not remember what it activated — a "No tools matched" answer for
68
+ // an ALREADY-ACTIVE tool would push it toward the exact wrong conclusion (capability missing).
69
+ // ponytail: naive keyword match (any query token as a case-insensitive substring of
70
+ // name+description) with a hard per-search activation cap above — the two named ceilings are
71
+ // relevance and irreversibility; swap in scoring/embeddings if catalogs outgrow this.
72
+ const tokens = input.query
73
+ .toLowerCase()
74
+ .split(/[^a-z0-9]+/)
75
+ .filter(Boolean);
76
+ // AND semantics: EVERY token must hit — "adding a word narrows" must actually hold, or the
77
+ // over-cap "narrow the query" instruction sends the model in circles (OR would widen with each
78
+ // word, and a shared prefix like "fetch" could make a whole tool family permanently over-cap).
79
+ const matchesQuery = (t) => {
80
+ const haystack = `${t.name} ${t.description}`.toLowerCase();
81
+ return tokens.every((token) => haystack.includes(token));
82
+ };
83
+ const describe = (t) => `${t.name} — ${t.description.split("\n")[0]}`;
84
+ const active = new Set(ctx.tools.active());
85
+ const registered = ctx.tools.registered();
86
+ // A query with no searchable tokens (all punctuation/symbols) must not match: `every` over an
87
+ // empty token list is vacuously true, and a noise query would otherwise activate the catalog.
88
+ if (tokens.length === 0)
89
+ return `"${input.query}" contains no searchable keywords — describe the capability you need.`;
90
+ // Exact-name shortcut: the guaranteed escape hatch from the cap — a query that IS an INACTIVE
91
+ // registered tool's name addresses that one tool, no keyword scoring in the way. An exact match
92
+ // on an ACTIVE tool falls through to keyword matching: it must not swallow the discovery of
93
+ // other, still-inactive keyword matches.
94
+ const exact = registered.find((t) => t.name.toLowerCase() === input.query.trim().toLowerCase());
95
+ const activeMatches = registered.filter((t) => active.has(t.name) && (t === exact || matchesQuery(t)));
96
+ const inactiveMatches = exact && !active.has(exact.name) ? [exact] : registered.filter((t) => !active.has(t.name) && matchesQuery(t));
97
+ // Same listing cap as every other branch — a wide token can match most of the ACTIVE set too
98
+ // (in chat that includes pi's default tools), and no answer may pour a catalog into the context.
99
+ const listedActive = activeMatches.slice(0, MAX_MISS_LISTING);
100
+ const moreActive = activeMatches.length - listedActive.length;
101
+ const activeNote = activeMatches.length > 0
102
+ ? `Already active (call directly): ${listedActive.map(describe).join("; ")}${moreActive > 0 ? ` … and ${moreActive} more` : ""}.`
103
+ : "";
104
+ if (inactiveMatches.length === 0) {
105
+ if (activeNote)
106
+ return activeNote;
107
+ const inactive = registered.filter((t) => !active.has(t.name));
108
+ if (inactive.length === 0)
109
+ return "All tools are already active — nothing to discover.";
110
+ // Cap the miss listing like the activation cap — both guard the same semantic (don't pour the
111
+ // catalog back into the context the deferral exists to protect).
112
+ const listed = inactive.slice(0, MAX_MISS_LISTING);
113
+ const more = inactive.length - listed.length;
114
+ return `No tools matched "${input.query}". Inactive tools: ${listed.map(describe).join("; ")}${more > 0 ? ` … and ${more} more — search with different keywords.` : ""}`;
115
+ }
116
+ if (inactiveMatches.length > MAX_ACTIVATIONS_PER_SEARCH) {
117
+ // Same listing cap as the miss path — an over-cap answer must not pour the catalog into the
118
+ // context either. Names alone suffice: the exact-name escape only needs a name to query.
119
+ const listed = inactiveMatches.slice(0, MAX_MISS_LISTING);
120
+ const more = inactiveMatches.length - listed.length;
121
+ return `${inactiveMatches.length} inactive tools matched "${input.query}" — too many to activate at once (activation is permanent for this conversation). Narrow the query (or query an exact name). Matches: ${listed
122
+ .map((t) => t.name)
123
+ .join(", ")}${more > 0 ? ` … and ${more} more` : ""}.${activeNote ? ` ${activeNote}` : ""}`;
124
+ }
125
+ const activated = await ctx.tools.activate(inactiveMatches.map((t) => t.name));
126
+ // Report what actually happened, not what was attempted: a parallel sibling call may have
127
+ // activated the same matches first, leaving nothing new here — an empty "Activated:" would lie.
128
+ if (activated.length === 0) {
129
+ return `Matched ${inactiveMatches.map((t) => t.name).join(", ")} — already active (possibly activated by a concurrent call). Call them directly.${activeNote ? ` ${activeNote}` : ""}`;
130
+ }
131
+ const raced = inactiveMatches.filter((t) => !activated.includes(t.name));
132
+ return `Activated: ${inactiveMatches
133
+ .filter((t) => activated.includes(t.name))
134
+ .map(describe)
135
+ .join("; ")}.${raced.length > 0 ? ` Already active: ${raced.map((t) => t.name).join(", ")}.` : ""}${activeNote ? ` ${activeNote}` : ""} These tools are callable now.`;
136
+ },
137
+ });
138
+ }
@@ -10,8 +10,36 @@
10
10
  * build time (e.g. a stateRoot) do NOT belong here — pass them via the tool's own closure.
11
11
  */
12
12
  import { AsyncLocalStorage } from "node:async_hooks";
13
+ /**
14
+ * The turn's tool-activation bridge — narrow closures over the CURRENT harness (invoke.ts builds it
15
+ * per turn), so a loader tool can activate deferred tools mid-turn without tool.ts importing the
16
+ * harness. pi records the change in the session (`active_tools_change`) and the per-invoke restore
17
+ * (harness.ts) carries it into later turns; defineTool's wrapper stamps the newly-activated names on
18
+ * the tool result (`addedToolNames`) — the load point native deferred-loading providers preserve the
19
+ * prompt-cache prefix with.
20
+ */
21
+ export interface ToolActivation {
22
+ /** Names of the currently ACTIVE tools. */
23
+ active(): string[];
24
+ /** Every registered tool (active or not) — the discovery corpus for a loader like `search_tools`. */
25
+ registered(): Array<{
26
+ name: string;
27
+ description: string;
28
+ }>;
29
+ /** ADDITIVE activation. Unknown names are filtered out before reaching pi (whose `setActiveTools`
30
+ * THROWS on them); resolves the names actually newly activated (already-active names don't repeat). */
31
+ activate(names: string[]): Promise<string[]>;
32
+ }
13
33
  export interface TurnContext {
14
34
  /** The session id of the current turn. */
15
35
  session: string;
36
+ /** Tool activation for the current turn. Two producers, one consumer surface: invoke.ts bridges the
37
+ * serving harness; chat.ts bridges pi's AgentSession (chat emulates deferral — same loader, same
38
+ * semantics). Absent only outside any turn (a bare `fastagent tool` run). */
39
+ tools?: ToolActivation;
16
40
  }
17
41
  export declare const turnContext: AsyncLocalStorage<TurnContext>;
42
+ /** The additive-activation contract, in ONE place for both bridges (invoke.ts over the harness,
43
+ * chat.ts over pi's AgentSession): dedupe → keep registered names only (pi's setters THROW on
44
+ * unknown) → exclude already-active → the names to actually add (empty = nothing to set). */
45
+ export declare function additiveActivation(registered: string[], current: string[], names: string[]): string[];
@@ -11,3 +11,11 @@
11
11
  */
12
12
  import { AsyncLocalStorage } from "node:async_hooks";
13
13
  export const turnContext = new AsyncLocalStorage();
14
+ /** The additive-activation contract, in ONE place for both bridges (invoke.ts over the harness,
15
+ * chat.ts over pi's AgentSession): dedupe → keep registered names only (pi's setters THROW on
16
+ * unknown) → exclude already-active → the names to actually add (empty = nothing to set). */
17
+ export function additiveActivation(registered, current, names) {
18
+ const known = new Set(registered);
19
+ const active = new Set(current);
20
+ return [...new Set(names)].filter((name) => known.has(name) && !active.has(name));
21
+ }
@@ -1,22 +1,53 @@
1
1
  import type { AgentTool } from "@earendil-works/pi-agent-core";
2
2
  import { z } from "zod";
3
3
  import { type ModuleLoadFailure } from "../../loader.ts";
4
+ import { type ToolActivation } from "./tool-context.ts";
4
5
  export interface ToolContext {
5
6
  /** Abort signal for the current turn — honor it to cancel in-flight work on cancellation. */
6
7
  signal?: AbortSignal;
7
8
  /** The session id of the current turn — which conversation this tool is running in. A general tool
8
9
  * capability: partition per-conversation data, tag logs, scope state. Undefined outside a turn (a bare
9
10
  * `fastagent tool` run, or any call with no session). (The built-in `wake` tool is one consumer — it
10
- * fires a later turn back into this same session.) */
11
+ * fires a later turn back into this same session.) In a `fastagent chat` turn this is pi's LOCAL
12
+ * chat session id, not a served session — serving-coupled consumers like wake are not mounted there. */
11
13
  session?: string;
14
+ /** Tool activation for the current turn (a loader tool activates {@link DefineToolOptions.deferred}
15
+ * tools with it — the built-in `search_tools` is one consumer). Provided by both the serving path
16
+ * (invoke.ts, over the harness) and chat (over pi's AgentSession); undefined only outside any turn
17
+ * (a bare `fastagent tool` run). */
18
+ tools?: ToolActivation;
12
19
  }
13
20
  export interface DefineToolOptions<I extends z.ZodType> {
14
21
  /** Explicit name. Usually omitted — a `tools/<name>.ts` tool is named from its filename. */
15
22
  name?: string;
16
23
  description: string;
17
24
  input: I;
25
+ /**
26
+ * Registered but NOT initially active: the tool's schema stays out of every request (and the model's
27
+ * sight) until a loader — the built-in `search_tools`, mounted automatically when any deferred tool
28
+ * exists — activates it mid-turn. For tool-heavy agents: fewer schemas per turn, and on providers
29
+ * with native deferred loading the activation preserves the prompt-cache prefix. The trade-off:
30
+ * discovery rides entirely on this description — write it for the search. Default: false.
31
+ */
32
+ deferred?: boolean;
33
+ /** pi's per-tool execution mode: "sequential" makes pi run any batch containing this tool serially.
34
+ * REQUIRED for a tool that activates others (a loader): pi's own diff around SDK tools (chat)
35
+ * would attribute one activation to two parallel calls otherwise. */
36
+ executionMode?: "sequential" | "parallel";
18
37
  execute: (input: z.infer<I>, ctx: ToolContext) => unknown | Promise<unknown>;
19
38
  }
39
+ /** An AgentTool with fastagent's deferral marker — the type for raw tools handed to fastagent
40
+ * (`config.tools`, L1/L2 `tools`): plain `AgentTool` has no `deferred`, so an object literal with the
41
+ * marker would fail excess-property checking against upstream's type. `defineTool` produces it. */
42
+ export type FastagentTool = AgentTool & {
43
+ deferred?: boolean;
44
+ };
45
+ /** Read the {@link DefineToolOptions.deferred} marker off a mounted tool (extra property on the
46
+ * AgentTool object — pi ignores it). */
47
+ export declare function isDeferredTool(tool: AgentTool): boolean;
48
+ /** The same tool without the deferred marker — for a loader that must stay active (a deferred loader
49
+ * could never be activated and would strand every deferred tool). */
50
+ export declare function stripDeferredMarker(tool: AgentTool): AgentTool;
20
51
  export declare function defineTool<I extends z.ZodType>(options: DefineToolOptions<I>): AgentTool;
21
52
  /** A discarded same-name tool (within `tools/`, or against an existing tool). Surfaced, never silent. */
22
53
  export interface ToolCollision {
@@ -14,6 +14,19 @@ import { join } from "node:path";
14
14
  import { z } from "zod";
15
15
  import { loadModuleDir } from "../../loader.js";
16
16
  import { turnContext } from "./tool-context.js";
17
+ /** Read the {@link DefineToolOptions.deferred} marker off a mounted tool (extra property on the
18
+ * AgentTool object — pi ignores it). */
19
+ export function isDeferredTool(tool) {
20
+ return tool.deferred === true;
21
+ }
22
+ /** The same tool without the deferred marker — for a loader that must stay active (a deferred loader
23
+ * could never be activated and would strand every deferred tool). */
24
+ export function stripDeferredMarker(tool) {
25
+ if (!isDeferredTool(tool))
26
+ return tool;
27
+ const { deferred: _drop, ...active } = tool;
28
+ return active;
29
+ }
17
30
  /** Wrap a plain return value into pi's tool-result shape; pass a full result through unchanged. */
18
31
  function wrapResult(value) {
19
32
  if (value && typeof value === "object" && Array.isArray(value.content)) {
@@ -28,6 +41,8 @@ export function defineTool(options) {
28
41
  name: options.name ?? "",
29
42
  description: options.description,
30
43
  parameters,
44
+ ...(options.deferred ? { deferred: true } : {}),
45
+ ...(options.executionMode ? { executionMode: options.executionMode } : {}),
31
46
  async execute(_toolCallId, rawParams, signal) {
32
47
  const parsed = options.input.safeParse(rawParams);
33
48
  if (!parsed.success) {
@@ -35,7 +50,33 @@ export function defineTool(options) {
35
50
  const detail = parsed.error.issues.map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`).join("; ");
36
51
  return { content: [{ type: "text", text: `Invalid arguments: ${detail}` }], details: { error: detail } };
37
52
  }
38
- return wrapResult(await options.execute(parsed.data, { signal, session: turnContext.getStore()?.session }));
53
+ const store = turnContext.getStore();
54
+ // Stamp tools THIS execute activates on its result — the load point that lets native
55
+ // deferred-loading providers add the definitions at this transcript position without
56
+ // invalidating the cached prompt prefix. The names come from this execute's OWN activate()
57
+ // calls (accumulated below), NOT from an active-set before/after diff: pi runs tool calls of a
58
+ // batch in parallel, and a snapshot diff would stamp a sibling's activation onto the wrong tool
59
+ // result, drifting the load point.
60
+ const added = [];
61
+ const tools = store?.tools
62
+ ? {
63
+ ...store.tools,
64
+ activate: async (names) => {
65
+ // biome-ignore lint/style/noNonNullAssertion: guarded by the ternary above
66
+ const activated = await store.tools.activate(names);
67
+ added.push(...activated);
68
+ return activated;
69
+ },
70
+ }
71
+ : undefined;
72
+ const result = wrapResult(await options.execute(parsed.data, { signal, session: store?.session, tools }));
73
+ if (added.length > 0) {
74
+ // A copy, not a mutation: wrapResult passes a full AgentToolResult through by REFERENCE, and an
75
+ // author may legally return a shared/frozen result object — stamping in place would corrupt it
76
+ // across calls (or throw on frozen), only on the rare activating path.
77
+ return { ...result, addedToolNames: [...new Set([...(result.addedToolNames ?? []), ...added])] };
78
+ }
79
+ return result;
39
80
  },
40
81
  };
41
82
  return tool;
@@ -45,8 +45,11 @@ export declare function createPiAgentFromWorkspace(dir: string, options?: Create
45
45
  sessionsDir: string;
46
46
  /** Absolute credentials file in use (for the startup report). */
47
47
  authPath: string;
48
- /** Non-default tool names in effect: config.tools + discovered tools/. */
48
+ /** Non-default, active-by-default tool names in effect: config.tools + discovered tools/. Each name
49
+ * lives in exactly one report slot — deferred names are in {@link deferredToolNames} instead. */
49
50
  toolNames: string[];
51
+ /** Tools registered but not initially active (deferred) — activated via search_tools. */
52
+ deferredToolNames: string[];
50
53
  toolCollisions: ToolCollision[];
51
54
  /** `tools/` files that failed to import — skipped, reported by the caller, never fatal. */
52
55
  toolFailures: ModuleLoadFailure[];
@@ -28,7 +28,7 @@ export async function createPiAgentFromWorkspace(dir, options = {}) {
28
28
  // The run root is `dir` (cwd — where config lives, whose AGENTS.md is ② context); the agent's own
29
29
  // surface (persona/skills/tools/channels) lives in `agentDir` (config.agentDir, or `dir` when flat).
30
30
  const agentDir = resolveAgentDir(dir, config);
31
- const { tools, toolNames, toolCollisions, toolFailures } = await resolveWorkspaceTools(config, agentDir, dir);
31
+ const { tools, toolNames, deferredToolNames, toolCollisions, toolFailures } = await resolveWorkspaceTools(config, agentDir, dir);
32
32
  // The state root: auth/sessions/channel state all derive from it, so FASTAGENT_STATE_DIR moves the
33
33
  // whole machine-state home in one knob (a container mounts one volume); the finer overrides below
34
34
  // still win for their specific path.
@@ -47,6 +47,7 @@ export async function createPiAgentFromWorkspace(dir, options = {}) {
47
47
  await ensureStateRootSelfIgnored(dir, stateRoot);
48
48
  const { agent, definition } = await createPiAgentFromDefinition(agentDir, {
49
49
  model: modelSpec,
50
+ thinkingLevel: config.thinkingLevel,
50
51
  cwd: dir,
51
52
  tools: mountedTools,
52
53
  authPath,
@@ -64,6 +65,7 @@ export async function createPiAgentFromWorkspace(dir, options = {}) {
64
65
  sessionsDir,
65
66
  authPath,
66
67
  toolNames,
68
+ deferredToolNames,
67
69
  toolCollisions,
68
70
  toolFailures,
69
71
  };
@@ -0,0 +1,2 @@
1
+ /** `@fastagent-sh/fastagent/feishu` — the canonical Feishu (open.feishu.cn) bot-channel surface. */
2
+ export { feishuChannel, defaultFeishuRoute, feishuEnvelope, type FeishuChannelOptions, type FeishuMessageEvent, type FeishuMessage, type FeishuRoute, type FeishuFailure, } from "./channels/feishu/feishu.ts";
package/dist/feishu.js ADDED
@@ -0,0 +1,2 @@
1
+ /** `@fastagent-sh/fastagent/feishu` — the canonical Feishu (open.feishu.cn) bot-channel surface. */
2
+ export { feishuChannel, defaultFeishuRoute, feishuEnvelope, } from "./channels/feishu/feishu.js";
package/dist/lark.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ /** `@fastagent-sh/fastagent/lark` — the Lark-international compatibility surface over the canonical
2
+ * Feishu engine. Feishu tenants use `@fastagent-sh/fastagent/feishu`. */
3
+ export { larkChannel, defaultLarkRoute, larkEnvelope, type LarkChannelOptions, type LarkMessageEvent, type LarkMessage, type LarkRoute, type LarkFailure, } from "./channels/lark/lark.ts";
package/dist/lark.js ADDED
@@ -0,0 +1,3 @@
1
+ /** `@fastagent-sh/fastagent/lark` — the Lark-international compatibility surface over the canonical
2
+ * Feishu engine. Feishu tenants use `@fastagent-sh/fastagent/feishu`. */
3
+ export { larkChannel, defaultLarkRoute, larkEnvelope, } from "./channels/lark/lark.js";
@@ -0,0 +1,2 @@
1
+ /** Best-effort open a URL in the default browser. Callers must also print the URL for headless use. */
2
+ export declare function openExternalUrl(url: string): void;
@@ -0,0 +1,6 @@
1
+ import { spawn } from "node:child_process";
2
+ /** Best-effort open a URL in the default browser. Callers must also print the URL for headless use. */
3
+ export function openExternalUrl(url) {
4
+ const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
5
+ spawn(cmd, [url], { stdio: "ignore", detached: true, shell: process.platform === "win32" }).on("error", () => { });
6
+ }
package/dist/pi.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { createPiAgent, createPiAgentFromDefinition, type CreatePiAgentFromDefinitionOptions, type CreatePiAgentOptions, } from "./engines/pi/create.ts";
2
- export { defineTool, loadTools, type DefineToolOptions, type ToolCollision, type ToolContext, } from "./engines/pi/tool.ts";
2
+ export { defineTool, loadTools, type DefineToolOptions, type FastagentTool, type ToolCollision, type ToolContext, } from "./engines/pi/tool.ts";
3
+ export type { ToolActivation } from "./engines/pi/tool-context.ts";
3
4
  export { z } from "zod";
4
5
  export type { AgentTool, ExecutionEnv, Session, Skill, SkillDiagnostic } from "@earendil-works/pi-agent-core";
5
6
  export { loadChannels, type ChannelCollision } from "./engines/pi/channel.ts";
@@ -1,8 +1,10 @@
1
- export type ChannelKind = "github" | "telegram";
1
+ export type ChannelKind = "github" | "telegram" | "feishu" | "lark";
2
2
  /** An env var a scaffolded channel reads. `generate` = a random-string secret the CLI can pre-fill. */
3
3
  export interface ChannelEnv {
4
4
  name: string;
5
5
  hint: string;
6
+ /** Required for the channel to run. Optional values are deployed when present but never gate deploy. */
7
+ required: boolean;
6
8
  generate?: boolean;
7
9
  }
8
10
  /** The channel kinds `fastagent add <kind>` can scaffold. */
@@ -26,11 +28,13 @@ export interface DotEnvWriteResult {
26
28
  }
27
29
  /**
28
30
  * Append generated channel secrets to the run-root `.env` (never `.env.example`) after the CLI has
29
- * verified that `.env` is gitignored. Existing non-empty values are kept. Manual values (e.g.
30
- * TELEGRAM_BOT_TOKEN from BotFather) are added only as commented placeholders, so the file is ready to
31
- * edit while no fake secret is committed to the user's mental model.
31
+ * verified that `.env` is gitignored. Existing non-empty values are kept EXCEPT the names listed in
32
+ * `overwrite`: those are authoritative (e.g. the credentials of an app `add feishu` JUST minted —
33
+ * skipping them for a stale value would silently discard a fresh, unrecoverable secret). Manual values
34
+ * (e.g. TELEGRAM_BOT_TOKEN from BotFather) are added only as commented placeholders, so the file is
35
+ * ready to edit while no fake secret is committed to the user's mental model.
32
36
  */
33
- export declare function appendChannelDotEnv(dir: string, kind: ChannelKind, generated: Record<string, string>): Promise<DotEnvWriteResult>;
37
+ export declare function appendChannelDotEnv(dir: string, kind: ChannelKind, generated: Record<string, string>, overwrite?: readonly string[]): Promise<DotEnvWriteResult>;
34
38
  /** Whether a channel file already exists — checked before any mutation, so a no-clobber re-add is side-effect-free. */
35
39
  export declare function channelExists(dir: string, kind: ChannelKind): Promise<boolean>;
36
40
  /**
@@ -17,6 +17,7 @@ const CHANNEL_SCAFFOLDS = {
17
17
  {
18
18
  name: "GITHUB_WEBHOOK_SECRET",
19
19
  hint: "any random string; set the same value in the GitHub webhook",
20
+ required: true,
20
21
  generate: true,
21
22
  },
22
23
  ],
@@ -29,14 +30,77 @@ const CHANNEL_SCAFFOLDS = {
29
30
  },
30
31
  telegram: {
31
32
  env: [
32
- { name: "TELEGRAM_BOT_TOKEN", hint: "from @BotFather → /newbot" },
33
- { name: "TELEGRAM_SECRET_TOKEN", hint: "any random string; verifies inbound updates", generate: true },
33
+ { name: "TELEGRAM_BOT_TOKEN", hint: "from @BotFather → /newbot", required: true },
34
+ {
35
+ name: "TELEGRAM_SECRET_TOKEN",
36
+ hint: "any random string; verifies inbound updates",
37
+ required: true,
38
+ generate: true,
39
+ },
34
40
  ],
35
41
  steps: [
36
42
  "edit {channel} — customise routing with route() (optional; the defaults already work)",
37
43
  "the agent can send messages or files back by calling the scaffolded {tools}/telegram-send.ts tool",
38
44
  ],
39
45
  },
46
+ // Feishu is the canonical engine/cloud; Lark international reuses its protocol through a degraded
47
+ // compatibility profile. Each remains its own channel KIND: route, env, state, console, onboarding.
48
+ // No `generate` in either: every value comes FROM the platform (a locally generated Encrypt Key
49
+ // would break inbound events until mirrored in the console). `add feishu` scan-creates the app;
50
+ // Lark lacks that control-plane capability, so `add lark` guides console credential collection.
51
+ feishu: {
52
+ env: [
53
+ {
54
+ name: "FEISHU_APP_ID",
55
+ hint: "created + written automatically by `add feishu` (console → Credentials & Basic Info)",
56
+ required: true,
57
+ },
58
+ {
59
+ name: "FEISHU_APP_SECRET",
60
+ hint: "created + written automatically by `add feishu` (console → Credentials & Basic Info)",
61
+ required: true,
62
+ },
63
+ {
64
+ name: "FEISHU_VERIFICATION_TOKEN",
65
+ hint: "captured automatically (console → Events & Callbacks)",
66
+ required: true,
67
+ },
68
+ {
69
+ name: "FEISHU_ENCRYPT_KEY",
70
+ hint: "optional but recommended — set one in the console and copy it here",
71
+ required: false,
72
+ },
73
+ ],
74
+ steps: [
75
+ "optional before publishing: add the sensitive im:message.group_msg permission (tenant-admin approval) to receive unmentioned managed-thread continuations and buffer other group discussion",
76
+ "PUBLISH the app version on the page the CLI opened — the switch to webhook mode takes effect on publish (one click, once ever; no API for it)",
77
+ "edit {channel} — routing policy (the header walks through the console setup, for hand-made apps)",
78
+ "the event Request URL is auto-registered by `dev --tunnel` / `deploy --run`",
79
+ "the agent can push messages from scheduled turns via the scaffolded {tools}/feishu-send.ts tool",
80
+ ],
81
+ },
82
+ lark: {
83
+ env: [
84
+ { name: "LARK_APP_ID", hint: "developer console → Credentials & Basic Info", required: true },
85
+ { name: "LARK_APP_SECRET", hint: "developer console → Credentials & Basic Info", required: true },
86
+ {
87
+ name: "LARK_VERIFICATION_TOKEN",
88
+ hint: "console → Events & Callbacks; authenticates inbound events",
89
+ required: true,
90
+ },
91
+ {
92
+ name: "LARK_ENCRYPT_KEY",
93
+ hint: "optional but recommended — set one in the console and copy it here",
94
+ required: false,
95
+ },
96
+ ],
97
+ steps: [
98
+ "finish the console setup: enable Bot and add the required permissions + im.message.receive_v1 event listed in {channel} (do not publish yet)",
99
+ "optional before publishing: add the sensitive im:message.group_msg permission (tenant-admin approval) to receive unmentioned managed-thread continuations and buffer other group discussion",
100
+ "run `fastagent dev --tunnel` and keep it running; if auto-registration reports a config-API 404, manually switch Subscription mode to webhook, set its printed https://…/lark Request URL, save, then create + publish a version",
101
+ "the agent can push messages from scheduled turns via the scaffolded {tools}/lark-send.ts tool",
102
+ ],
103
+ },
40
104
  };
41
105
  /** The channel kinds `fastagent add <kind>` can scaffold. */
42
106
  export const CHANNEL_KINDS = Object.keys(CHANNEL_SCAFFOLDS);
@@ -83,11 +147,13 @@ function mentionsEnvName(content, name) {
83
147
  }
84
148
  /**
85
149
  * Append generated channel secrets to the run-root `.env` (never `.env.example`) after the CLI has
86
- * verified that `.env` is gitignored. Existing non-empty values are kept. Manual values (e.g.
87
- * TELEGRAM_BOT_TOKEN from BotFather) are added only as commented placeholders, so the file is ready to
88
- * edit while no fake secret is committed to the user's mental model.
150
+ * verified that `.env` is gitignored. Existing non-empty values are kept EXCEPT the names listed in
151
+ * `overwrite`: those are authoritative (e.g. the credentials of an app `add feishu` JUST minted —
152
+ * skipping them for a stale value would silently discard a fresh, unrecoverable secret). Manual values
153
+ * (e.g. TELEGRAM_BOT_TOKEN from BotFather) are added only as commented placeholders, so the file is
154
+ * ready to edit while no fake secret is committed to the user's mental model.
89
155
  */
90
- export async function appendChannelDotEnv(dir, kind, generated) {
156
+ export async function appendChannelDotEnv(dir, kind, generated, overwrite = []) {
91
157
  const file = join(dir, ".env");
92
158
  let current = "";
93
159
  try {
@@ -97,7 +163,9 @@ export async function appendChannelDotEnv(dir, kind, generated) {
97
163
  if (e.code !== "ENOENT")
98
164
  throw e;
99
165
  }
100
- const alreadySet = CHANNEL_SCAFFOLDS[kind].env.filter((e) => hasActiveEnvValue(current, e.name)).map((e) => e.name);
166
+ const alreadySet = CHANNEL_SCAFFOLDS[kind].env
167
+ .filter((e) => !overwrite.includes(e.name) && hasActiveEnvValue(current, e.name))
168
+ .map((e) => e.name);
101
169
  const lines = [];
102
170
  const written = [];
103
171
  const contentLines = current.split("\n");
@@ -7,6 +7,7 @@
7
7
  // you have access to (`fastagent models` lists them).
8
8
  export default {
9
9
  // model: "openai-codex/gpt-5.5",
10
+ // thinkingLevel: "high", // reasoning effort (off|minimal|low|medium|high|xhigh|max); default "medium" (pi TUI parity)
10
11
  http: { port: 8787 },
11
12
  // selfSchedule: true, // mount the built-in `wake` tool: the agent schedules its own follow-up turns
12
13
  // // ("check the deploy in 10 min"). Cron jobs need no opt-in — drop a schedules/<name>.ts.
package/dist/tunnel.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * `--tunnel`: expose the local dev server on a public HTTPS URL via a Cloudflare quick tunnel, then
3
- * auto-register the first-party webhook channels against it (telegram setWebhook; github prints the
4
- * URL to paste into repo settings). This closes the "local dev → public URL" gap webhooks need.
3
+ * auto-register the first-party webhook channels against it (Telegram setWebhook; Feishu/Lark
4
+ * application-config PATCH; GitHub prints the URL to paste into repo settings). This closes the
5
+ * "local dev → public URL" gap webhooks need.
5
6
  *
6
7
  * Process orchestration, not assembly — lives outside the engine, beside dev-supervisor.ts.
7
8
  */
@@ -22,10 +23,12 @@ type SpawnCloudflared = (port: number) => ChildProcess;
22
23
  * (Edge warmup AFTER the URL appears is handled downstream: the telegram registrar polls /health before
23
24
  * it calls setWebhook, so a not-yet-routable tunnel just delays registration rather than failing it.)
24
25
  */
25
- export declare function startCloudflareTunnel(port: number, spawnFn?: SpawnCloudflared): Promise<Tunnel | undefined>;
26
+ export declare function startCloudflareTunnel(port: number, spawnFn?: SpawnCloudflared, attemptTimeoutMs?: number): Promise<Tunnel | undefined>;
26
27
  /**
27
- * Print the public URL and wire up the first-party webhook channels found under `dir`: telegram is
28
- * auto-registered via setWebhook (using .env tokens); github prints the URL to add in repo settings.
28
+ * Print the public URL and wire up the first-party webhook channels found under `dir`: Telegram and
29
+ * Feishu/Lark auto-register using credentials from .env; GitHub prints the URL to add in repo settings.
29
30
  */
30
- export declare function announceWebhooks(dir: string, baseUrl: string): Promise<void>;
31
+ export declare function announceWebhooks(dir: string, baseUrl: string, opts?: {
32
+ openUrl?: (url: string) => void;
33
+ }): Promise<void>;
31
34
  export {};