aismemory 0.8.8 → 0.8.10

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 (68) hide show
  1. package/README.md +38 -7
  2. package/dist/agent-key-mode.d.ts +26 -0
  3. package/dist/agent-key-mode.js +165 -26
  4. package/dist/agent-only-pass.d.ts +41 -0
  5. package/dist/agent-only-pass.js +539 -0
  6. package/dist/ais-http.d.ts +11 -0
  7. package/dist/ais-http.js +31 -17
  8. package/dist/cli/hooks.d.ts +35 -5
  9. package/dist/cli/hooks.js +280 -66
  10. package/dist/cli/install.d.ts +8 -0
  11. package/dist/cli/install.js +15 -0
  12. package/dist/cli/orientation-load.d.ts +18 -0
  13. package/dist/cli/orientation-load.js +50 -0
  14. package/dist/cli/read-claude-memory-tree.d.ts +37 -0
  15. package/dist/cli/read-claude-memory-tree.js +247 -2
  16. package/dist/cli/setup-core.js +7 -3
  17. package/dist/cli/slack.d.ts +2 -0
  18. package/dist/cli/slack.js +263 -0
  19. package/dist/cli/sync-memory.js +13 -5
  20. package/dist/cli-info.d.ts +1 -0
  21. package/dist/cli-info.js +6 -0
  22. package/dist/decision-card.d.ts +42 -0
  23. package/dist/decision-card.js +50 -0
  24. package/dist/decision-ledger.d.ts +24 -0
  25. package/dist/decision-ledger.js +59 -0
  26. package/dist/decision-receipt.d.ts +33 -0
  27. package/dist/decision-receipt.js +72 -0
  28. package/dist/device-poll.d.ts +16 -7
  29. package/dist/device-poll.js +31 -3
  30. package/dist/handoff-doc.d.ts +9 -0
  31. package/dist/handoff-doc.js +53 -0
  32. package/dist/inbox-client.js +33 -26
  33. package/dist/index.js +298 -71
  34. package/dist/mcp/tools.d.ts +5 -0
  35. package/dist/mcp/tools.js +121 -31
  36. package/dist/operating-layer-read.d.ts +38 -0
  37. package/dist/operating-layer-read.js +164 -0
  38. package/dist/pending-device-flow.d.ts +2 -0
  39. package/dist/pending-device-flow.js +1 -0
  40. package/dist/pipeline/bulk-store.d.ts +4 -3
  41. package/dist/pipeline/bulk-store.js +45 -8
  42. package/dist/pipeline/ingestion.d.ts +1 -0
  43. package/dist/pipeline/ingestion.js +6 -1
  44. package/dist/pipeline/types.d.ts +4 -0
  45. package/dist/recall-warning.d.ts +14 -0
  46. package/dist/recall-warning.js +36 -0
  47. package/dist/request-timeout.d.ts +27 -2
  48. package/dist/request-timeout.js +92 -2
  49. package/dist/run-pass-mode.js +34 -16
  50. package/dist/session-identity.js +3 -1
  51. package/dist/session-start.d.ts +13 -3
  52. package/dist/session-start.js +53 -10
  53. package/dist/skill-fetch.d.ts +30 -0
  54. package/dist/skill-fetch.js +88 -0
  55. package/dist/slack-tools.d.ts +44 -0
  56. package/dist/slack-tools.js +156 -0
  57. package/dist/sources/local-claude.js +16 -2
  58. package/dist/sources/types.d.ts +2 -0
  59. package/dist/startup-identity.d.ts +4 -0
  60. package/dist/startup-identity.js +2 -0
  61. package/dist/tool-args.d.ts +12 -1
  62. package/dist/tool-args.js +15 -0
  63. package/dist/tool-scope-filter.d.ts +29 -0
  64. package/dist/tool-scope-filter.js +123 -0
  65. package/dist/version-check.d.ts +30 -3
  66. package/dist/version-check.js +59 -4
  67. package/dist/workspace-key-mode.js +36 -22
  68. package/package.json +4 -3
package/README.md CHANGED
@@ -37,7 +37,7 @@ Add to your IDE's MCP server config:
37
37
  "mcpServers": {
38
38
  "aismemory": {
39
39
  "command": "npx",
40
- "args": ["aismemory@0.8.8"],
40
+ "args": ["aismemory@0.8.10"],
41
41
  "env": {
42
42
  "npm_config_audit": "false",
43
43
  "npm_config_fund": "false"
@@ -85,10 +85,19 @@ This adds two entries to `.claude/settings.json` and keeps everything already
85
85
  there. If you commit that file, the hooks run for every teammate who opens the
86
86
  project, with their own credentials. Add `--local` to write
87
87
  `.claude/settings.local.json` for yourself only. `--dry-run` shows the result
88
- without writing it.
88
+ without writing it. `aismemory hooks print` shows the two entries and your
89
+ user-level `~/.claude/settings.json` (every session, any folder) without
90
+ changing any file; `--dir ~` on `install` writes them there.
91
+
89
92
 
90
93
  - **SessionStart** loads your agent's goals, last handoff and recent memories
91
94
  into each new Claude Code session, marked as recalled data, not instructions.
95
+ Its first line says whether your agent's rules loaded
96
+ (`RULES v<version> loaded (<n> rules)`). If they could not load within 5
97
+ seconds, it says `RULES NOT LOADED` and why, and shows the last good copy
98
+ saved on this computer. Without a credential it prints nothing. After
99
+ Claude Code compacts the conversation, it shows the rules again.
100
+ The saved-copy fallback works for workspace-key and agent-key sign-ins only; enrolled-key sign-ins are tracked in CORBOT-9CEA4E23.
92
101
  - **PreCompact** saves a handoff (folder, git branch, uncommitted files and
93
102
  your last message, with keys and passwords removed) before Claude Code
94
103
  compacts the conversation.
@@ -102,11 +111,14 @@ unreachable, they print one warning line and let the session carry on.
102
111
  | Tool | Description |
103
112
  |------|-------------|
104
113
  | `remember` | Store a memory (fact, event, lesson, context, goal, task). Answers with a short receipt (`id`, `agentId`, `tier`, `createdAt`, `tokenEstimate`, and `supersedes` when given); pass `verbose: true` for the whole stored memory |
114
+ | `update_memory` | Update your existing memory by UUID: optional content, importance, tags or metadata; omitted fields stay unchanged and `tags: []` clears caller-managed tags. AIS preserves server-managed tags and controls protected metadata fields. Requires at least one update field. Available with owner sign-in, agent key, workspace key or run pass. |
105
115
  | `recall` | Search memories by natural language query |
106
116
  | `memory_get` | Read one memory in full by id, for a result that recall returned cut (`truncated: true`) |
107
117
  | `memory_forget` | Retire one of your own memories by its full id: recall and `full_context` leave it out from then on. It is kept, not deleted (marked expired now). Own memories only; takes no agent argument |
108
118
  | `whoami` | Get agent identity and status |
109
- | `orientation_check` | Diff an owner-approved expected-environment manifest against this session's evidence — read-only, same comparator as `aismemory doctor --orientation`, reachable without a filesystem |
119
+ | `skill_fetch` | Fetch a published fleet skill body (`desk`, `ooo`, or `floor`) from AIS and verify its hash. Unpublished or access-gated skills return `SKILL-UNAVAILABLE`; does not auto-install |
120
+ | `environment_manifest_get` | Read the owner-approved expected-environment manifest stored on this identity. Names and purposes only. Read-only; an owner publishes it |
121
+ | `orientation_check` | Diff an owner-approved expected-environment manifest against this session's evidence — read-only, same comparator as `aismemory doctor --orientation`. Pass the manifest, or omit requirements to load the one stored on this identity |
110
122
  | `full_context` | Load complete agent context (personality, goals, facts, skills, and the versioned operating layer — constitution rules plus the skills index). On `view=lean` or `view=bootstrap`, memories tagged `no-lean` are omitted unless you pass your own `tags`, `anyTags`, or `excludeTags`. |
111
123
  | `dream` | Trigger memory consolidation (promotes important, archives old). Long runs go async: the client polls up to `AIS_DREAM_POLL_MS` (default 120000) and otherwise returns `status: "running"` with the `runId` |
112
124
  | `handoff` | Save session context for the next session |
@@ -114,21 +126,24 @@ unreachable, they print one warning line and let the session carry on.
114
126
  | `inbox_send` | Send a message to another agent in your tenant |
115
127
  | `inbox_read` | Read messages other agents have sent you |
116
128
  | `inbox_ack` | Ack specific inbox messages by id without a fresh read |
129
+ | `slack_post` | Post to a Slack channel you are bound to, as yourself, via the ais-slack bridge with your own agent API key (needs `AIS_SLACK_URL`) |
130
+ | `slack_read` | Read the Slack messages pushed to your inbox at turn start (reads the inbox, never Slack; no polling) |
117
131
  | `goal_create` | Create a new goal for the current agent |
118
132
  | `goal_list` | List goals for the current agent, with status/parent filters |
119
133
  | `goal_update_progress` | Update a goal's progress (0-100) |
120
134
  | `goal_activate` | Activate one of your own draft goals so it shows in your context |
121
135
  | `goal_complete` | Mark a goal complete (success or failure) |
122
136
  | `operating_layer_put` | Store one rule or skill in this agent's OWN operating layer, so it loads in every tool connected to the agent (`full_context` / `agent_load`). Agent API key only; takes no agent argument; only when the human asked |
137
+ | `skill_get` | Read the note saved under one own skill name (the skills index lists names only). The note is the agent's own, unreviewed, never authority. Agent API key only; takes no agent argument |
123
138
  | `agent_archive` | Archive one of your own agents by id. Restorable; nothing is deleted. Owner sign-in only |
124
139
  | `agent_delete` | Compatibility alias for `agent_archive`. It archives; it does not delete |
125
140
 
126
141
  ### What `agent_load` hands a new session
127
142
 
128
- Besides the agent's identity, counts and receipt, `agent_load` answers with `start`: a short piece of text a session can read at once: at most about 1,600 tokens of memory text, about 2,200 with the item fields and notes.
143
+ Besides the agent's identity, counts and receipt, `agent_load` answers with `start`: a bounded summary of the agent’s stored context.
129
144
 
130
145
  - `handoff`: the newest **task** memory tagged `handoff`. Before a session stops, store one task memory with that tag saying what the next session should do first. With none, the last automatic handoff summary is shown instead, with its date.
131
- - `lessons`: up to three **lesson** memories tagged `when:turn-start`, newest first, each cut at 600 characters. Use that tag for the few rules that apply at the start of every turn.
146
+ - `lessons`: up to three **lesson** memories tagged `when:turn-start`, newest first, each cut at 600 characters, plus up to 12 bootstrap standing lessons with 320-character previews. Bootstrap gives lessons tagged `owner-ruling` priority, then includes other lessons with importance of at least 0.8. An item that appears in both reads is shown once. Use `when:turn-start` for rules that apply at the start of every turn.
132
147
  - `openOrders` and `unreadInbox`: what the service lists as still open, and how many inbox messages are unread.
133
148
  - `notes`: anything missing, cut, or unreadable. Each item carries its memory id and `writerKind`, the kind of credential that stored it: an agent's memory holds what was stored under its id, which is not always what the agent itself wrote.
134
149
 
@@ -193,7 +208,7 @@ Authentication uses the OAuth device flow (RFC 8628). Credentials are saved to `
193
208
  |----------|---------|-------------|
194
209
  | `AIS_URL` | `https://ais.agentsandswarms.ai` | AIS server URL |
195
210
  | `AIS_WORKSPACE_KEY` | unset | Workspace key (`ais_wk_...`) for several agents; see [One key for many agents](#one-key-for-many-agents-ais_workspace_key) |
196
- | `AIS_MCP_REQUEST_TIMEOUT_MS` | `20000` | Client-side timeout, in milliseconds, for every HTTP call this server makes to AIS. A stalled call fails with a clear error instead of hanging. Must be a positive number; anything else falls back to the default |
211
+ | `AIS_MCP_REQUEST_TIMEOUT_MS` | `9000` | Client-side timeout, in milliseconds, for every HTTP call this server makes to AIS. A stalled call fails with a clear error instead of hanging. Must be a positive number; anything else falls back to the default |
197
212
  | `AISMEMORY_VERSION_CHECK` | on | Set to `off` to stop the daily check for a newer published version of this package |
198
213
 
199
214
  ## Unattended machines (agent API keys)
@@ -296,6 +311,22 @@ precedence over saved sign-in. If `AIS_RUN_PASS_FILE` is set together with
296
311
  `AIS_WORKSPACE_KEY`, `AIS_AGENT_API_KEY`, or `AIS_API_KEY`, startup is refused
297
312
  instead of silently falling back to a long-lived key.
298
313
 
314
+ To forbid step 4 on a machine, set `AIS_REQUIRE_AGENT_KEY=1` (`1`, `true`,
315
+ `yes` or `on`, any case). If none of `AIS_API_KEY`, `AIS_AGENT_API_KEY`,
316
+ `AIS_WORKSPACE_KEY` or `AIS_RUN_PASS_FILE` is set, aismemory prints an error
317
+ and exits instead of using the saved owner sign-in, which can reach every
318
+ agent the owner has. It is off by default because an owner session may pick
319
+ an agent with `AIS_AGENT_ID` alone. Unset, empty, `0`, `false`, `no` or `off`
320
+ leave it off; any other value refuses to start, so a typo never leaves it off.
321
+
322
+ The check covers the MCP server and every subcommand. `hooks`, `setup` and
323
+ `doctor` need an agent credential, as the server does. `enable-key-auth`,
324
+ `rotate-token`, `api-keys` and `agents` exist to use the owner sign-in, so
325
+ they are always refused. `install`, `invite`, `sync`, `pull` and
326
+ `export-harness` never read the saved owner sign-in and run as usual. The
327
+ flag stops aismemory from using the owner sign-in; it is not a sandbox, and
328
+ any process with a shell on the machine can still read a saved sign-in file.
329
+
299
330
  ## One key for many agents (`AIS_WORKSPACE_KEY`)
300
331
 
301
332
  If you run several agents, the owner of those agents can mint one
@@ -325,7 +356,7 @@ mint a new one.
325
356
  "mcpServers": {
326
357
  "aismemory": {
327
358
  "command": "npx",
328
- "args": ["aismemory@0.8.8"],
359
+ "args": ["aismemory@0.8.10"],
329
360
  "env": {
330
361
  "AIS_WORKSPACE_KEY": "ais_wk_...",
331
362
  "AIS_AGENT_ID": "<the agent to start with>",
@@ -18,6 +18,32 @@ export declare class AgentApiKeyConfigError extends Error {
18
18
  * mode exists to kill).
19
19
  */
20
20
  export declare function loadAgentApiKeyConfig(env?: Record<string, string | undefined>): AgentApiKeyConfig | null;
21
+ /**
22
+ * Reads AIS_REQUIRE_AGENT_KEY (trimmed, case-insensitive). Fails closed: a
23
+ * value that is neither on nor off throws instead of silently leaving strict
24
+ * mode off, so a typo in a security opt-in never falls back to the owner
25
+ * sign-in.
26
+ */
27
+ export declare function requireAgentKeyEnabled(env?: Record<string, string | undefined>): boolean;
28
+ /**
29
+ * Opt-in strict mode (CORBOT-8E24660B): with AIS_REQUIRE_AGENT_KEY on,
30
+ * refuse to start unless one of the scoped credential env vars is set.
31
+ * Without this, a missing key falls through to the stored owner sign-in
32
+ * (keychain or ~/.aismemory credentials), which carries owner_session reach
33
+ * over every agent the owner has. Opt-in because owner sessions may
34
+ * legitimately pick an agent with AIS_AGENT_ID alone.
35
+ *
36
+ * Presence only: each credential mode validates its own value (empty, wrong
37
+ * prefix, missing AIS_AGENT_ID) and refuses on its own.
38
+ */
39
+ export declare function assertAgentKeyWhenRequired(env?: Record<string, string | undefined>): void;
40
+ /**
41
+ * Strict-mode guard for every CLI entry path (`command` is argv[2]; undefined
42
+ * means the MCP server). Owner-only commands are refused outright; commands
43
+ * that never read the saved sign-in pass; everything else, including any
44
+ * future command, needs an agent credential, as the MCP server does.
45
+ */
46
+ export declare function assertStrictModeAllowsCommand(command: string | undefined, env?: Record<string, string | undefined>): void;
21
47
  type FetchImpl = typeof globalThis.fetch;
22
48
  export declare function aisKeyPost(aisUrl: string, path: string, apiKey: string, body: unknown, fetchImpl?: FetchImpl): Promise<unknown>;
23
49
  export declare function aisKeyGet(aisUrl: string, path: string, apiKey: string, fetchImpl?: FetchImpl): Promise<unknown>;
@@ -19,21 +19,25 @@
19
19
  * out-of-scope route return an honest error instead of making a request the
20
20
  * server would reject anyway.
21
21
  */
22
+ import { parseSlackPostArgs, parseSlackReadArgs, resolveSlackPostConfig, runSlackPost, runSlackRead } from './slack-tools.js';
23
+ import { handoffDocFields, withHandoffDocWarning } from './handoff-doc.js';
22
24
  import { AisHttpError, duplicateMemoryResult } from './ais-http-error.js';
23
- import { AIS_GET_RETRYABLE_STATUSES, AIS_GET_RETRY_DELAY_MS } from './ais-http.js';
25
+ import { AIS_GET_RETRYABLE_STATUSES, AIS_GET_RETRY_DELAY_MS, captureServerVersionHeaders, withAisClientVersion, } from './ais-http.js';
24
26
  import { captureCredentialExpiry, withCredentialExpiry } from './credential-expiry.js';
25
- import { orient } from './cli/orientation.js';
27
+ import { orientAgainstStoredManifest } from './cli/orientation-load.js';
26
28
  import { emitTelemetry } from './telemetry.js';
27
29
  import { retryAfterOf, shouldHonourRetryAfter, sleepSeconds } from './retry-after.js';
28
- import { getAisRequestTimeoutMs, toAisRequestError } from './request-timeout.js';
30
+ import { aisRequestSignal, getAisRequestTimeoutMs, isAisRequestTimeout, setInboxReadStage, toAisRequestError } from './request-timeout.js';
29
31
  import { withDeclaredAgent } from './declared-agent.js';
30
- import { parseEmptyToolArgs, parseRecallArgs, parseMemoryGetArgs, buildMemoryGetPath, shapeMemoryGetResult, buildFullContextQuery, parseFullContextArgs, buildRememberStoreBody, shapeRememberResult, parseRememberArgs, parseInboxSendArgs, parseInboxReadArgs, parseGoalCreateArgs, parseGoalListArgs, parseGoalUpdateProgressArgs, parseGoalActivateArgs, parseGoalCompleteArgs, parseInboxAckArgs, parseHandoffArgs, } from './tool-args.js';
32
+ import { parseEmptyToolArgs, parseRecallArgs, parseMemoryGetArgs, buildMemoryGetPath, shapeMemoryGetResult, buildFullContextQuery, parseFullContextArgs, buildRememberStoreBody, shapeRememberResult, parseRememberArgs, parseUpdateMemoryArgs, parseInboxSendArgs, parseInboxReadArgs, parseGoalCreateArgs, parseGoalListArgs, parseGoalUpdateProgressArgs, parseGoalActivateArgs, parseGoalCompleteArgs, parseInboxAckArgs, parseHandoffArgs, } from './tool-args.js';
31
33
  import { readInboxAndMaybeAck } from './inbox-client.js';
32
34
  import { AGENT_ARCHIVE_KEY_MODE_DETAIL } from './agent-archive.js';
35
+ import { getOperatingLayerSkill, SKILL_GET_TOOL } from './operating-layer-read.js';
33
36
  import { OPERATING_LAYER_PUT_TOOL, putOperatingLayerEntry } from './operating-layer-write.js';
34
37
  import { fetchCredentialWhoami } from './credential-whoami.js';
35
38
  import { resolveDreamResponse } from './dream-poll.js';
36
39
  import { forgetOwnMemory } from './memory-forget.js';
40
+ import { skillFetch, SkillFetchError } from './skill-fetch.js';
37
41
  /** Thrown by loadAgentApiKeyConfig when AIS_AGENT_API_KEY is set without AIS_AGENT_ID. */
38
42
  export class AgentApiKeyConfigError extends Error {
39
43
  constructor(message) {
@@ -86,16 +90,90 @@ export function loadAgentApiKeyConfig(env = process.env) {
86
90
  }
87
91
  return { apiKey, agentId };
88
92
  }
89
- async function readJson(res) {
93
+ /** Env vars that each select a scoped (non-owner) credential mode. */
94
+ const AGENT_CREDENTIAL_ENV_NAMES = ['AIS_API_KEY', 'AIS_AGENT_API_KEY', 'AIS_WORKSPACE_KEY', 'AIS_RUN_PASS_FILE'];
95
+ const STRICT_ON_VALUES = ['1', 'true', 'yes', 'on'];
96
+ const STRICT_OFF_VALUES = ['', '0', 'false', 'no', 'off'];
97
+ /**
98
+ * Reads AIS_REQUIRE_AGENT_KEY (trimmed, case-insensitive). Fails closed: a
99
+ * value that is neither on nor off throws instead of silently leaving strict
100
+ * mode off, so a typo in a security opt-in never falls back to the owner
101
+ * sign-in.
102
+ */
103
+ export function requireAgentKeyEnabled(env = process.env) {
104
+ const raw = env['AIS_REQUIRE_AGENT_KEY'];
105
+ if (raw === undefined)
106
+ return false;
107
+ const flag = raw.trim().toLowerCase();
108
+ if (STRICT_ON_VALUES.includes(flag))
109
+ return true;
110
+ if (STRICT_OFF_VALUES.includes(flag))
111
+ return false;
112
+ throw new AgentApiKeyConfigError('AIS_REQUIRE_AGENT_KEY has a value that is not recognised.\n' +
113
+ `Use ${STRICT_ON_VALUES.join(', ')} to turn strict mode on, or ` +
114
+ `${STRICT_OFF_VALUES.filter((v) => v !== '').join(', ')} (or leave it unset or empty) to turn it off.\n` +
115
+ 'Refusing to start rather than guess.');
116
+ }
117
+ /**
118
+ * Opt-in strict mode (CORBOT-8E24660B): with AIS_REQUIRE_AGENT_KEY on,
119
+ * refuse to start unless one of the scoped credential env vars is set.
120
+ * Without this, a missing key falls through to the stored owner sign-in
121
+ * (keychain or ~/.aismemory credentials), which carries owner_session reach
122
+ * over every agent the owner has. Opt-in because owner sessions may
123
+ * legitimately pick an agent with AIS_AGENT_ID alone.
124
+ *
125
+ * Presence only: each credential mode validates its own value (empty, wrong
126
+ * prefix, missing AIS_AGENT_ID) and refuses on its own.
127
+ */
128
+ export function assertAgentKeyWhenRequired(env = process.env) {
129
+ if (!requireAgentKeyEnabled(env))
130
+ return;
131
+ if (AGENT_CREDENTIAL_ENV_NAMES.some((name) => env[name] !== undefined))
132
+ return;
133
+ const agentId = env['AIS_AGENT_ID']?.trim();
134
+ const target = agentId ? `agent ${agentId}` : 'this session';
135
+ throw new AgentApiKeyConfigError(`AIS_REQUIRE_AGENT_KEY is set but no agent credential is configured for ${target}.\n` +
136
+ `Set one of ${AGENT_CREDENTIAL_ENV_NAMES.join(', ')}.\n` +
137
+ 'Refusing to start: falling back to the saved owner sign-in would give this ' +
138
+ 'process reach over every agent the owner has.');
139
+ }
140
+ /** Subcommands that exist to use the owner sign-in; strict mode always refuses them. */
141
+ const OWNER_ONLY_COMMANDS = ['enable-key-auth', 'rotate-token', 'api-keys', 'agents'];
142
+ /**
143
+ * Subcommands that never read the saved owner sign-in: install writes config
144
+ * only, invite uses an invite token, sync/pull/export-harness take keys from
145
+ * env only and refuse without one.
146
+ */
147
+ const NO_OWNER_SIGN_IN_COMMANDS = ['install', 'invite', 'sync', 'pull', 'export-harness'];
148
+ /**
149
+ * Strict-mode guard for every CLI entry path (`command` is argv[2]; undefined
150
+ * means the MCP server). Owner-only commands are refused outright; commands
151
+ * that never read the saved sign-in pass; everything else, including any
152
+ * future command, needs an agent credential, as the MCP server does.
153
+ */
154
+ export function assertStrictModeAllowsCommand(command, env = process.env) {
155
+ if (!requireAgentKeyEnabled(env))
156
+ return;
157
+ if (command !== undefined && OWNER_ONLY_COMMANDS.includes(command)) {
158
+ throw new AgentApiKeyConfigError(`aismemory ${command} needs the owner sign-in, which AIS_REQUIRE_AGENT_KEY forbids on this machine.\n` +
159
+ 'Refusing to start. Run it where AIS_REQUIRE_AGENT_KEY is unset.');
160
+ }
161
+ if (command !== undefined && NO_OWNER_SIGN_IN_COMMANDS.includes(command))
162
+ return;
163
+ assertAgentKeyWhenRequired(env);
164
+ }
165
+ async function readJson(res, path, method = 'GET') {
90
166
  const warning = captureCredentialExpiry(res);
167
+ setInboxReadStage(`${method} ${path}: body`);
91
168
  const data = await res.json().catch(() => null);
169
+ setInboxReadStage(`${method} ${path}: body`);
92
170
  return withCredentialExpiry(data, warning);
93
171
  }
94
172
  export async function aisKeyPost(aisUrl, path, apiKey, body, fetchImpl = globalThis.fetch) {
95
- const headers = withDeclaredAgent({
173
+ const headers = withDeclaredAgent(withAisClientVersion({
96
174
  'Content-Type': 'application/json',
97
175
  'x-agent-api-key': apiKey,
98
- });
176
+ }));
99
177
  const timeoutMs = getAisRequestTimeoutMs();
100
178
  let res;
101
179
  try {
@@ -103,7 +181,7 @@ export async function aisKeyPost(aisUrl, path, apiKey, body, fetchImpl = globalT
103
181
  method: 'POST',
104
182
  headers,
105
183
  body: JSON.stringify(body),
106
- signal: AbortSignal.timeout(timeoutMs),
184
+ signal: aisRequestSignal(path, timeoutMs, 'POST'),
107
185
  });
108
186
  }
109
187
  catch (err) {
@@ -111,7 +189,8 @@ export async function aisKeyPost(aisUrl, path, apiKey, body, fetchImpl = globalT
111
189
  emitTelemetry({ event: 'ais.http.failure', path, error: wrapped instanceof Error ? wrapped.message : String(wrapped) });
112
190
  throw wrapped;
113
191
  }
114
- const data = await readJson(res);
192
+ captureServerVersionHeaders(res);
193
+ const data = await readJson(res, path, 'POST');
115
194
  if (!res.ok) {
116
195
  emitTelemetry({ event: 'ais.http.failure', path, httpStatus: res.status, error: `HTTP ${res.status}` });
117
196
  throw new AisHttpError(res.status, path, data, retryAfterOf(res));
@@ -125,11 +204,20 @@ export async function aisKeyGet(aisUrl, path, apiKey, fetchImpl = globalThis.fet
125
204
  for (;;) {
126
205
  try {
127
206
  res = await fetchImpl(`${aisUrl}${path}`, {
128
- headers: withDeclaredAgent({ 'x-agent-api-key': apiKey }),
129
- signal: AbortSignal.timeout(timeoutMs),
207
+ headers: withDeclaredAgent(withAisClientVersion({ 'x-agent-api-key': apiKey })),
208
+ signal: aisRequestSignal(path, timeoutMs),
130
209
  });
131
210
  }
132
211
  catch (err) {
212
+ // CORBOT-9C5DC76D: a thrown transport error (e.g. TypeError "fetch
213
+ // failed") gets the same single retry as a 502/503. A timeout is not
214
+ // retried, so the caller never waits twice the timeout.
215
+ if (attempt === 0 && !isAisRequestTimeout(err)) {
216
+ attempt += 1;
217
+ emitTelemetry({ event: 'ais.http.retry', path, error: err instanceof Error ? err.message : String(err) });
218
+ await new Promise((resolve) => setTimeout(resolve, AIS_GET_RETRY_DELAY_MS));
219
+ continue;
220
+ }
133
221
  const wrapped = toAisRequestError(err, path, timeoutMs);
134
222
  emitTelemetry({ event: 'ais.http.failure', path, error: wrapped instanceof Error ? wrapped.message : String(wrapped) });
135
223
  throw wrapped;
@@ -149,6 +237,7 @@ export async function aisKeyGet(aisUrl, path, apiKey, fetchImpl = globalThis.fet
149
237
  captureCredentialExpiry(res);
150
238
  attempt += 1;
151
239
  emitTelemetry({ event: 'ais.http.retry', path, httpStatus: res.status });
240
+ setInboxReadStage(`GET ${path}: retry delay`);
152
241
  if (retryAfter === null) {
153
242
  await new Promise((resolve) => setTimeout(resolve, AIS_GET_RETRY_DELAY_MS));
154
243
  }
@@ -159,7 +248,8 @@ export async function aisKeyGet(aisUrl, path, apiKey, fetchImpl = globalThis.fet
159
248
  }
160
249
  break;
161
250
  }
162
- const data = await readJson(res);
251
+ captureServerVersionHeaders(res);
252
+ const data = await readJson(res, path);
163
253
  if (!res.ok) {
164
254
  emitTelemetry({ event: 'ais.http.failure', path, httpStatus: res.status, error: `HTTP ${res.status}` });
165
255
  throw new AisHttpError(res.status, path, data, retryAfterOf(res));
@@ -167,10 +257,10 @@ export async function aisKeyGet(aisUrl, path, apiKey, fetchImpl = globalThis.fet
167
257
  return data;
168
258
  }
169
259
  export async function aisKeyPatch(aisUrl, path, apiKey, body, fetchImpl = globalThis.fetch) {
170
- const headers = withDeclaredAgent({
260
+ const headers = withDeclaredAgent(withAisClientVersion({
171
261
  'Content-Type': 'application/json',
172
262
  'x-agent-api-key': apiKey,
173
- });
263
+ }));
174
264
  const timeoutMs = getAisRequestTimeoutMs();
175
265
  let res;
176
266
  try {
@@ -178,7 +268,7 @@ export async function aisKeyPatch(aisUrl, path, apiKey, body, fetchImpl = global
178
268
  method: 'PATCH',
179
269
  headers,
180
270
  body: JSON.stringify(body),
181
- signal: AbortSignal.timeout(timeoutMs),
271
+ signal: aisRequestSignal(path, timeoutMs, 'PATCH'),
182
272
  });
183
273
  }
184
274
  catch (err) {
@@ -186,7 +276,8 @@ export async function aisKeyPatch(aisUrl, path, apiKey, body, fetchImpl = global
186
276
  emitTelemetry({ event: 'ais.http.failure', path, error: wrapped instanceof Error ? wrapped.message : String(wrapped) });
187
277
  throw wrapped;
188
278
  }
189
- const data = await readJson(res);
279
+ captureServerVersionHeaders(res);
280
+ const data = await readJson(res, path, 'PATCH');
190
281
  if (!res.ok) {
191
282
  emitTelemetry({ event: 'ais.http.failure', path, httpStatus: res.status, error: `HTTP ${res.status}` });
192
283
  throw new AisHttpError(res.status, path, data, retryAfterOf(res));
@@ -194,10 +285,10 @@ export async function aisKeyPatch(aisUrl, path, apiKey, body, fetchImpl = global
194
285
  return data;
195
286
  }
196
287
  export async function aisKeyPut(aisUrl, path, apiKey, body, fetchImpl = globalThis.fetch) {
197
- const headers = withDeclaredAgent({
288
+ const headers = withDeclaredAgent(withAisClientVersion({
198
289
  'Content-Type': 'application/json',
199
290
  'x-agent-api-key': apiKey,
200
- });
291
+ }));
201
292
  const timeoutMs = getAisRequestTimeoutMs();
202
293
  let res;
203
294
  try {
@@ -205,7 +296,7 @@ export async function aisKeyPut(aisUrl, path, apiKey, body, fetchImpl = globalTh
205
296
  method: 'PUT',
206
297
  headers,
207
298
  body: JSON.stringify(body),
208
- signal: AbortSignal.timeout(timeoutMs),
299
+ signal: aisRequestSignal(path, timeoutMs, 'PUT'),
209
300
  });
210
301
  }
211
302
  catch (err) {
@@ -213,7 +304,8 @@ export async function aisKeyPut(aisUrl, path, apiKey, body, fetchImpl = globalTh
213
304
  emitTelemetry({ event: 'ais.http.failure', path, error: wrapped instanceof Error ? wrapped.message : String(wrapped) });
214
305
  throw wrapped;
215
306
  }
216
- const data = await readJson(res);
307
+ captureServerVersionHeaders(res);
308
+ const data = await readJson(res, path, 'PUT');
217
309
  if (!res.ok) {
218
310
  emitTelemetry({ event: 'ais.http.failure', path, httpStatus: res.status, error: `HTTP ${res.status}` });
219
311
  throw new AisHttpError(res.status, path, data, retryAfterOf(res));
@@ -253,6 +345,10 @@ export async function dispatchToolKeyMode(aisUrl, config, name, rawArgs, fetchIm
253
345
  throw err;
254
346
  }
255
347
  }
348
+ case 'update_memory': {
349
+ const { memoryId, ...update } = parseUpdateMemoryArgs(rawArgs);
350
+ return aisKeyPatch(aisUrl, `/v1/agents/${agentId}/memory/${memoryId}`, apiKey, update, fetchImpl);
351
+ }
256
352
  case 'recall': {
257
353
  const args = parseRecallArgs(rawArgs);
258
354
  const params = new URLSearchParams();
@@ -280,7 +376,7 @@ export async function dispatchToolKeyMode(aisUrl, config, name, rawArgs, fetchIm
280
376
  const fcArgs = parseFullContextArgs(rawArgs);
281
377
  const fcQs = buildFullContextQuery(fcArgs);
282
378
  const fcPath = `/v1/agents/${agentId}/full-context${fcQs}`;
283
- return aisKeyGet(aisUrl, fcPath, apiKey, fetchImpl);
379
+ return withHandoffDocWarning(await aisKeyGet(aisUrl, fcPath, apiKey, fetchImpl));
284
380
  }
285
381
  case 'dream':
286
382
  parseEmptyToolArgs(rawArgs);
@@ -293,11 +389,15 @@ export async function dispatchToolKeyMode(aisUrl, config, name, rawArgs, fetchIm
293
389
  // the bare identity route the server now allowlists for agent API keys.
294
390
  return fetchCredentialWhoami(agentId, 'agent-api-key', () => aisKeyGet(aisUrl, `/v1/agents/${agentId}/whoami`, apiKey, fetchImpl), () => aisKeyGet(aisUrl, `/v1/agents/${agentId}`, apiKey, fetchImpl));
295
391
  }
392
+ case 'environment_manifest_get':
393
+ parseEmptyToolArgs(rawArgs);
394
+ return aisKeyGet(aisUrl, `/v1/agents/${agentId}/environment-manifest`, apiKey, fetchImpl);
296
395
  case 'orientation_check':
297
- // Pure, read-only, local comparison — no AIS round trip, no scope check
298
- // needed. orient() validates its own input and throws on a malformed
299
- // manifest; the caller's outer catch turns that into an {error} result.
300
- return orient(rawArgs);
396
+ // Requirements in the arguments stay a local comparison. Omitting them
397
+ // loads the owner-approved manifest AIS stores for this identity, then
398
+ // runs the same diff. A malformed manifest throws; the outer catch
399
+ // turns that into an {error} result.
400
+ return orientAgainstStoredManifest(rawArgs, agentId, () => aisKeyGet(aisUrl, `/v1/agents/${agentId}/environment-manifest`, apiKey, fetchImpl));
301
401
  case 'inbox_send': {
302
402
  const args = parseInboxSendArgs(rawArgs);
303
403
  return aisKeyPost(aisUrl, `/v1/agents/${agentId}/inbox`, apiKey, {
@@ -320,6 +420,15 @@ export async function dispatchToolKeyMode(aisUrl, config, name, rawArgs, fetchIm
320
420
  params.set('unreadOnly', String(args.unreadOnly));
321
421
  return readInboxAndMaybeAck(args, () => aisKeyGet(aisUrl, `/v1/agents/${agentId}/inbox?${params}`, apiKey, fetchImpl), (messageIds) => aisKeyPost(aisUrl, `/v1/agents/${agentId}/inbox/ack`, apiKey, { messageIds }, fetchImpl));
322
422
  }
423
+ case 'slack_post': {
424
+ const args = parseSlackPostArgs(rawArgs);
425
+ return runSlackPost(resolveSlackPostConfig(process.env, apiKey), agentId, args, fetchImpl);
426
+ }
427
+ case 'slack_read': {
428
+ const args = parseSlackReadArgs(rawArgs);
429
+ const params = new URLSearchParams({ limit: String(args.limit), unreadOnly: 'true' });
430
+ return runSlackRead(args, () => aisKeyGet(aisUrl, `/v1/agents/${agentId}/inbox?${params}`, apiKey, fetchImpl), (messageIds) => aisKeyPost(aisUrl, `/v1/agents/${agentId}/inbox/ack`, apiKey, { messageIds }, fetchImpl));
431
+ }
323
432
  case 'inbox_ack': {
324
433
  const args = parseInboxAckArgs(rawArgs);
325
434
  return aisKeyPost(aisUrl, `/v1/agents/${agentId}/inbox/ack`, apiKey, { messageIds: args.messageIds }, fetchImpl);
@@ -371,19 +480,49 @@ export async function dispatchToolKeyMode(aisUrl, config, name, rawArgs, fetchIm
371
480
  return aisKeyPost(aisUrl, `/v1/agents/${agentId}/handoff`, apiKey, {
372
481
  ...(args.summary !== undefined ? { summary: args.summary } : {}),
373
482
  ...(args.keyLearnings !== undefined ? { keyLearnings: args.keyLearnings } : {}),
374
- ...(args.docPath !== undefined ? { docPath: args.docPath } : {}),
483
+ ...await handoffDocFields(args.docPath),
375
484
  ...(args.docPrUrl !== undefined ? { docPrUrl: args.docPrUrl } : {}),
376
485
  }, fetchImpl);
377
486
  }
378
487
  case OPERATING_LAYER_PUT_TOOL:
379
488
  // The target is the key's own agent; the tool takes no agent argument.
380
489
  return putOperatingLayerEntry(agentId, rawArgs, (path, body) => aisKeyPut(aisUrl, path, apiKey, body, fetchImpl), (path) => aisKeyGet(aisUrl, path, apiKey, fetchImpl));
490
+ case SKILL_GET_TOOL:
491
+ return getOperatingLayerSkill(agentId, rawArgs, (path) => aisKeyGet(aisUrl, path, apiKey, fetchImpl));
381
492
  case 'agent_load':
382
493
  throw new OutOfScopeToolError('agent_load', 'switching agents requires a tenant-wide agent-listing route, which is outside the ' +
383
494
  "key's allowed scope. The active agent is fixed to AIS_AGENT_ID for the life of this process.");
384
495
  case 'agent_archive':
385
496
  case 'agent_delete':
386
497
  throw new OutOfScopeToolError(name, AGENT_ARCHIVE_KEY_MODE_DETAIL);
498
+ case 'skill_fetch': {
499
+ const fetchName = typeof rawArgs.name === 'string'
500
+ ? rawArgs.name
501
+ : '';
502
+ const fetchVersion = typeof rawArgs.version === 'string'
503
+ ? rawArgs.version
504
+ : undefined;
505
+ if (!fetchName) {
506
+ throw new Error('skill_fetch requires name');
507
+ }
508
+ try {
509
+ return await skillFetch({ name: fetchName, ...(fetchVersion !== undefined ? { version: fetchVersion } : {}) }, {
510
+ aisUrl,
511
+ agentId,
512
+ token: apiKey,
513
+ getJson: async (url) => {
514
+ const path = new URL(url).pathname;
515
+ return aisKeyGet(aisUrl, path, apiKey, fetchImpl);
516
+ },
517
+ });
518
+ }
519
+ catch (err) {
520
+ if (err instanceof SkillFetchError) {
521
+ throw new Error(`${err.code}: ${err.message}`);
522
+ }
523
+ throw err;
524
+ }
525
+ }
387
526
  default:
388
527
  return UNKNOWN_TOOL_KEY_MODE;
389
528
  }
@@ -0,0 +1,41 @@
1
+ import { z } from 'zod';
2
+ import { aisPost } from './ais-http.js';
3
+ declare const active: z.ZodObject<{
4
+ key_id: z.ZodString;
5
+ expires_at: z.ZodString;
6
+ agent_id: z.ZodString;
7
+ tenant_id: z.ZodString;
8
+ read_only: z.ZodBoolean;
9
+ key: z.ZodString;
10
+ minted_at: z.ZodString;
11
+ ais_origin: z.ZodString;
12
+ rotate_after_ms: z.ZodOptional<z.ZodNumber>;
13
+ }, z.core.$strip>;
14
+ type Pass = z.infer<typeof active>;
15
+ export declare function agentOnlyPassPath(): string;
16
+ export declare function loadAgentOnlyPass(file: string, origin: string, now?: number): Pass;
17
+ export declare function bondAgentOnly(file: string, origin: string, options: {
18
+ name: string;
19
+ mode?: 'reauth';
20
+ harness: string;
21
+ }, post: typeof aisPost, log: (message: string) => void): Promise<void>;
22
+ export declare class AgentOnlyPass {
23
+ private readonly file;
24
+ private readonly origin;
25
+ private readonly log;
26
+ private readonly send;
27
+ private readonly now;
28
+ private queue;
29
+ private agentId?;
30
+ constructor(file: string, origin: string, log: (message: string) => void, send?: typeof fetch, now?: () => number);
31
+ initialize(): Promise<string>;
32
+ startRenewal(): void;
33
+ readonly fetch: typeof fetch;
34
+ private enqueue;
35
+ private currentPass;
36
+ private end;
37
+ private deferRotation;
38
+ private rotateIfDue;
39
+ private confirmSuccessor;
40
+ }
41
+ export {};