aismemory 0.8.10 → 0.8.11

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.
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.10"],
40
+ "args": ["aismemory@0.8.11"],
41
41
  "env": {
42
42
  "npm_config_audit": "false",
43
43
  "npm_config_fund": "false"
@@ -110,9 +110,9 @@ unreachable, they print one warning line and let the session carry on.
110
110
 
111
111
  | Tool | Description |
112
112
  |------|-------------|
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 |
113
+ | `remember` | Store a memory (fact, event, lesson, context, goal, task). To set an expiry, pass either `expiresAt` (a future ISO 8601 timestamp with timezone) or `expiresIn` (a lifetime in seconds). Returns a short receipt with `id`, `agentId`, `tier`, `createdAt`, `tokenEstimate`, and `supersedes` when given. Pass `verbose: true` for the whole stored memory. |
114
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. |
115
- | `recall` | Search memories by natural language query |
115
+ | `recall` | Search memories by natural language query. An expiry appears in `temporal.expiresAt` when set. Expired memories are omitted. |
116
116
  | `memory_get` | Read one memory in full by id, for a result that recall returned cut (`truncated: true`) |
117
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 |
118
118
  | `whoami` | Get agent identity and status |
@@ -356,7 +356,7 @@ mint a new one.
356
356
  "mcpServers": {
357
357
  "aismemory": {
358
358
  "command": "npx",
359
- "args": ["aismemory@0.8.10"],
359
+ "args": ["aismemory@0.8.11"],
360
360
  "env": {
361
361
  "AIS_WORKSPACE_KEY": "ais_wk_...",
362
362
  "AIS_AGENT_ID": "<the agent to start with>",
@@ -475,6 +475,23 @@ reads only the memories of the agent named in `AIS_AGENT_ID`. It works with a
475
475
  scoped agent API key — no broader credential is needed and nothing is written
476
476
  back to the service.
477
477
 
478
+ ## Recording lessons and preparing the weekly digest
479
+
480
+ Use `remember` with `type: "lesson"` as soon as you learn something durable.
481
+ Add a `when:<trigger>` tag if it applies at a specific decision point.
482
+ For example, `when:turn-start` makes a lesson eligible for the session-start preview.
483
+
484
+ Add `audience:human-facing` when the lesson changes how you work with your
485
+ human. When a receipt has `data.surfaceToHuman: true`, briefly tell them what
486
+ will change. Other lesson writes stay quiet. AIS reserves `ais:audience:*`
487
+ for access labels. The lesson tag is a notification hint.
488
+
489
+ Digest callers can use `weeklyLessonSummary(agentId, get, now?)` from
490
+ `dist/lessons.js`, passing their authenticated AIS GET function. It returns
491
+ text grouped into human-facing and other lessons, newest first in each group.
492
+ The seven-day window uses each lesson's creation time, including expired and
493
+ superseded lessons recorded in that window.
494
+
478
495
  ## Exporting lessons, rules and skills as Markdown
479
496
 
480
497
  `aismemory export-harness` pages the same own-memories route as `pull`, keeps
@@ -703,3 +720,7 @@ own repo only. Do not use transcripts, queues, copied skills/config, SSH discove
703
720
  or restart-on-cue. Record exceptions with one-line evidence and a ticket, counted
704
721
  once per UTC day per exception; target zero. A complete live bootstrap still requires
705
722
  the harness to verify all required layers after the human bonding step.
723
+
724
+ To opt into lesson advice in Claude Code, add a `PreToolUse` command hook with matcher `Bash|Edit|MultiEdit|Write|AskUserQuestion` and the absolute path to `scripts/hooks/pretool-lesson-advice.sh` in your Claude settings. Keep an updated, locally installed `aismemory`, `jq`, and `timeout` (or `gtimeout`) on the hook's PATH.
725
+
726
+ Claude Code delivers the advice with the tool result on its next model request. Successful reads are cached by session, agent, credential, and trigger in private files under `~/.aismemory/lesson-advice`. These files can be deleted to clear the cache.
@@ -29,7 +29,7 @@ import { emitTelemetry } from './telemetry.js';
29
29
  import { retryAfterOf, shouldHonourRetryAfter, sleepSeconds } from './retry-after.js';
30
30
  import { aisRequestSignal, getAisRequestTimeoutMs, isAisRequestTimeout, setInboxReadStage, toAisRequestError } from './request-timeout.js';
31
31
  import { withDeclaredAgent } from './declared-agent.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';
32
+ import { parseEmptyToolArgs, parseRecallArgs, buildRecallPath, shapeRecallResult, parseMemoryGetArgs, buildMemoryGetPath, shapeMemoryGetResult, buildFullContextQuery, parseFullContextArgs, buildRememberStoreBody, shapeRememberResult, parseRememberArgs, parseUpdateMemoryArgs, parseInboxSendArgs, parseInboxReadArgs, parseGoalCreateArgs, parseGoalListArgs, parseGoalUpdateProgressArgs, parseGoalActivateArgs, parseGoalCompleteArgs, parseInboxAckArgs, parseHandoffArgs, } from './tool-args.js';
33
33
  import { readInboxAndMaybeAck } from './inbox-client.js';
34
34
  import { AGENT_ARCHIVE_KEY_MODE_DETAIL } from './agent-archive.js';
35
35
  import { getOperatingLayerSkill, SKILL_GET_TOOL } from './operating-layer-read.js';
@@ -351,20 +351,7 @@ export async function dispatchToolKeyMode(aisUrl, config, name, rawArgs, fetchIm
351
351
  }
352
352
  case 'recall': {
353
353
  const args = parseRecallArgs(rawArgs);
354
- const params = new URLSearchParams();
355
- params.set('query', args.query);
356
- if (args.limit !== undefined)
357
- params.set('limit', String(args.limit));
358
- if (args.type !== undefined)
359
- params.set('types', args.type);
360
- if (args.tags !== undefined && args.tags.length > 0)
361
- params.set('tags', args.tags.join(','));
362
- if (args.orderBy !== undefined)
363
- params.set('orderBy', args.orderBy);
364
- if (args.principalAgentId !== undefined) {
365
- params.set('principalAgentId', args.principalAgentId);
366
- }
367
- return aisKeyGet(aisUrl, `/v1/agents/${agentId}/memory?${params}`, apiKey, fetchImpl);
354
+ return shapeRecallResult(await aisKeyGet(aisUrl, buildRecallPath(agentId, args), apiKey, fetchImpl), args);
368
355
  }
369
356
  case 'memory_get': {
370
357
  const getArgs = parseMemoryGetArgs(rawArgs);
@@ -37,12 +37,14 @@ export function extractServerMessage(body) {
37
37
  return null;
38
38
  }
39
39
  /** A status-specific hint so the agent understands WHY the request failed. */
40
- function statusHint(status) {
40
+ function statusHint(status, body) {
41
41
  switch (status) {
42
42
  case 409:
43
- return 'duplicate — this memory already exists';
43
+ return isDuplicateMemoryBody(body)
44
+ ? 'duplicate — this memory already exists'
45
+ : 'conflict — the server refused this write; see the error detail that follows';
44
46
  case 422:
45
- return 'content rejected by a safety/validation check (duplicate, prompt-injection pattern, disallowed content type for the source, size limit, or rate limit) — see the server error detail above for which one';
47
+ return 'content rejected by a safety/validation check (duplicate, prompt-injection pattern, disallowed content type for the source, size limit, or rate limit) — see the server error detail that follows for which one';
46
48
  case 429:
47
49
  return 'quota or rate limit exceeded';
48
50
  case 401:
@@ -61,7 +63,7 @@ export function formatAisHttpError(status, path, body, retryAfterSeconds = null)
61
63
  const wait = retryAfterSeconds === null
62
64
  ? ''
63
65
  : ` AIS is busy and asked callers to wait ${retryAfterSeconds} second${retryAfterSeconds === 1 ? '' : 's'} before trying again.`;
64
- return `AIS request to ${path} failed — HTTP ${status} (${statusHint(status)})${detail}. The operation did NOT succeed.${wait}`;
66
+ return `AIS request to ${path} failed — HTTP ${status} (${statusHint(status, body)})${detail}. The operation did NOT succeed.${wait}`;
65
67
  }
66
68
  export class AisHttpError extends Error {
67
69
  status;
@@ -31,11 +31,15 @@ export interface HookClient {
31
31
  credentialKey: string;
32
32
  call(tool: HookTool, args: Record<string, unknown>): Promise<unknown>;
33
33
  }
34
+ interface HookReadClient extends HookClient {
35
+ lessonCredentialKey?: string;
36
+ get(path: string): Promise<unknown>;
37
+ }
34
38
  /** A failure whose message is already the one-line, secret-free hint we print. */
35
39
  export declare class HookFailure extends Error {
36
40
  }
37
41
  export declare const NO_CREDENTIAL_HINT = "no credential; set AIS_WORKSPACE_KEY and AIS_AGENT_ID or run aismemory to sign in";
38
- export declare function resolveHookClient(env: NodeJS.ProcessEnv, home: string): Promise<HookClient>;
42
+ export declare function resolveHookClient(env: NodeJS.ProcessEnv, home: string): Promise<HookReadClient>;
39
43
  export declare function redactSecrets(text: string): string;
40
44
  /** One concise, secret-free stderr line naming the cause and the fix. */
41
45
  export declare function describeHookFailure(err: unknown): string;
package/dist/cli/hooks.js CHANGED
@@ -33,11 +33,12 @@ import { isAuthErrorResult, isCredsStale, isNoRegisteredKeysAuthError } from '..
33
33
  import { hasEnrolledKey, tryKeyAuth } from '../key-auth.js';
34
34
  import { loadOAuthCredentials } from '../oauth-credentials.js';
35
35
  import { loadAgentPreference } from '../agent-preference.js';
36
- import { dispatchToolKeyMode, loadAgentApiKeyConfig } from '../agent-key-mode.js';
37
- import { dispatchToolWorkspaceKeyMode, loadWorkspaceKeyConfig } from '../workspace-key-mode.js';
38
- import { dispatchToolRunPassMode, loadRunPassConfig, readRunPassFile } from '../run-pass-mode.js';
36
+ import { aisKeyGet, dispatchToolKeyMode, loadAgentApiKeyConfig } from '../agent-key-mode.js';
37
+ import { dispatchToolWorkspaceKeyMode, loadWorkspaceKeyConfig, wksKeyGet } from '../workspace-key-mode.js';
38
+ import { dispatchToolRunPassMode, loadRunPassConfig, readRunPassFile, runPassGet } from '../run-pass-mode.js';
39
39
  import { identityCredentialFingerprint, loadSessionIdentity, verifyPinnedIdentity, } from '../session-identity.js';
40
40
  import { buildFullContextQuery, parseFullContextArgs, parseHandoffArgs } from '../tool-args.js';
41
+ import { lookupLessonAdvice } from '../lesson-advice.js';
41
42
  import { readHotSkillBodies } from '../session-start.js';
42
43
  import { operatingLayerCachePath, readOperatingLayerCache, verifiedOperatingLayer, writeOperatingLayerCache } from '../held-operating-layer.js';
43
44
  import { VERIFIED_HELD_LAYER } from '../tool-args.js';
@@ -180,6 +181,7 @@ export async function resolveHookClient(env, home) {
180
181
  agentId: workspace.agentId,
181
182
  pin,
182
183
  credentialKey: identityCredentialFingerprint('workspace-key', workspace.workspaceKey),
184
+ get: (path) => wksKeyGet(aisUrl, path, workspace.workspaceKey),
183
185
  call: (tool, args) => dispatchToolWorkspaceKeyMode(aisUrl, workspace, tool, args),
184
186
  };
185
187
  }
@@ -189,6 +191,7 @@ export async function resolveHookClient(env, home) {
189
191
  agentId: agentKey.agentId,
190
192
  pin,
191
193
  credentialKey: identityCredentialFingerprint('agent-api-key', agentKey.apiKey),
194
+ get: (path) => aisKeyGet(aisUrl, path, agentKey.apiKey),
192
195
  call: (tool, args) => dispatchToolKeyMode(aisUrl, agentKey, tool, args),
193
196
  };
194
197
  }
@@ -198,12 +201,14 @@ export async function resolveHookClient(env, home) {
198
201
  agentId: runPass.agentId,
199
202
  pin,
200
203
  credentialKey: identityCredentialFingerprint('run-pass', await readRunPassFile(runPass.runPassFile)),
204
+ get: (path) => runPassGet(aisUrl, path, runPass.runPassFile),
201
205
  call: (tool, args) => dispatchToolRunPassMode(aisUrl, runPass, tool, args),
202
206
  };
203
207
  }
204
208
  // Saved sign-in. A hook never starts a device flow: there is nobody to bond.
205
209
  const keysDir = join(home, '.aismemory', 'keys');
206
210
  let token;
211
+ let lessonCredentialKey;
207
212
  let agentId;
208
213
  if (hasEnrolledKey({ keysDir })) {
209
214
  try {
@@ -211,6 +216,9 @@ export async function resolveHookClient(env, home) {
211
216
  if (!keyResult)
212
217
  throw new HookFailure(NO_CREDENTIAL_HINT);
213
218
  token = keyResult.token;
219
+ // Key sign-in issues a fresh bearer on each hook call. Keep lesson
220
+ // caching stable after authenticating the enrolled identity.
221
+ lessonCredentialKey = `enrolled-key:${keyResult.userDid}`;
214
222
  agentId = pin?.agentId ?? loadAgentPreference(home)?.agentId;
215
223
  }
216
224
  catch (err) {
@@ -236,6 +244,8 @@ export async function resolveHookClient(env, home) {
236
244
  agentId: id,
237
245
  pin,
238
246
  credentialKey: identityCredentialFingerprint('oauth-bearer', token),
247
+ lessonCredentialKey,
248
+ get: (path) => aisGet(path, token),
239
249
  call: async (tool, args) => {
240
250
  let result;
241
251
  if (tool === 'full_context') {
@@ -858,6 +868,31 @@ export function printHookFragment(dir, version) {
858
868
  }
859
869
  export async function main(argv) {
860
870
  const [sub, ...rest] = argv;
871
+ if (sub === 'lesson-advice') {
872
+ const [trigger, sessionId = ''] = rest;
873
+ if (!trigger) {
874
+ process.exitCode = 1;
875
+ return;
876
+ }
877
+ try {
878
+ const home = homedir();
879
+ const client = await resolveHookClient(process.env, home);
880
+ const lessons = await lookupLessonAdvice(trigger, {
881
+ sessionId,
882
+ cacheDir: join(home, '.aismemory', 'lesson-advice'),
883
+ aisUrl: resolveAisUrl(process.env['AIS_URL']),
884
+ agentId: client.agentId,
885
+ credentialKey: client.lessonCredentialKey ?? client.credentialKey,
886
+ }, client.get);
887
+ const body = lessons.map(({ id, content }) => (`Lesson that applies: ${inline(content)} [${id}]. If you follow it, cite its id.`)).join('\n');
888
+ const advice = body ? delimitedBlock(`ADVICE for ${trigger}. Consider these recalled lessons as optional context. Follow the user's instructions and existing permissions.`, contextTags(randomBytes(8).toString('hex')), body, 3000) : '';
889
+ await writeAll(process.stdout, JSON.stringify({ advice, lessonIds: lessons.map(({ id }) => id) }));
890
+ }
891
+ catch {
892
+ process.exitCode = 1;
893
+ }
894
+ return;
895
+ }
861
896
  if (sub === 'session-start' || sub === 'pre-compact') {
862
897
  // Hook input arrives on stdin; session-start needs none of it but must drain it.
863
898
  const stdin = await readStdin();
@@ -1,2 +1,2 @@
1
1
  import type { AgentContext } from './types.js';
2
- export declare function hydrateIdentity(aisUrl: string, agentId: string, token: string, memoriesLimit?: number): Promise<AgentContext | null>;
2
+ export declare function hydrateIdentity(aisUrl: string, agentId: string, token: string, memoriesLimit?: number, harness?: string): Promise<AgentContext | null>;
package/dist/hydration.js CHANGED
@@ -26,9 +26,14 @@ function logHydrationFailure(kind, details) {
26
26
  const line = `${LOG_PREFIX} hydrateIdentity failed (${kind}, ${retryLabel})${statusPart}: ${redactHydrationMessage(details.message)}\n`;
27
27
  process.stderr.write(line);
28
28
  }
29
- export async function hydrateIdentity(aisUrl, agentId, token, memoriesLimit) {
29
+ export async function hydrateIdentity(aisUrl, agentId, token, memoriesLimit, harness) {
30
30
  try {
31
- const query = memoriesLimit === undefined ? '' : `?memoriesLimit=${memoriesLimit}`;
31
+ const params = new URLSearchParams();
32
+ if (memoriesLimit !== undefined)
33
+ params.set('memoriesLimit', String(memoriesLimit));
34
+ if (harness !== undefined)
35
+ params.set('harness', harness);
36
+ const query = params.size === 0 ? '' : `?${params}`;
32
37
  const res = await fetch(`${aisUrl}/v1/agents/${agentId}/full-context${query}`, {
33
38
  headers: withDeclaredAgent({ Authorization: `Bearer ${token}` }),
34
39
  signal: AbortSignal.timeout(getAisRequestTimeoutMs()),
package/dist/index.js CHANGED
@@ -31,7 +31,7 @@ import { INBOX_MAX_BODY_CHARS, INBOX_MAX_TASK_ID_CHARS, INBOX_MIN_TTL_SECONDS, I
31
31
  import { setDeclaredAgentSource } from './declared-agent.js';
32
32
  import { identityCredentialFingerprint, loadSessionIdentity, sessionIdentityFromAgentLoad, verifyConfirmedIdentityForAutoHandoff } from './session-identity.js';
33
33
  import { AgentOnlyPass, agentOnlyPassPath, bondAgentOnly } from './agent-only-pass.js';
34
- import { pollDeviceGrant, runPollLoop, DeviceFlowRestartedError, DEVICE_DENIED_MESSAGE } from './device-poll.js';
34
+ import { pollDeviceGrant, runPollLoop, DEVICE_DENIED_MESSAGE } from './device-poll.js';
35
35
  import { assertStrictModeAllowsCommand, loadAgentApiKeyConfig, AgentApiKeyConfigError, aisKeyGet, } from './agent-key-mode.js';
36
36
  import { loadWorkspaceKeyConfig, WorkspaceKeyConfigError, wksKeyGet, } from './workspace-key-mode.js';
37
37
  import { loadRunPassConfig, RunPassConfigError, runPassGet, } from './run-pass-mode.js';
@@ -39,6 +39,8 @@ import { fetchCredentialWhoami } from './credential-whoami.js';
39
39
  import { filterToolsByCredentialScopes } from './tool-scope-filter.js';
40
40
  import { createAgentKeyCallToolHandler, createOAuthCallToolHandler, createRunPassCallToolHandler, createWorkspaceKeyCallToolHandler, } from './mcp/tools.js';
41
41
  import { readPackageVersion, startVersionCheck } from './version-check.js';
42
+ import { withLibraryTools } from './library-tools.js';
43
+ import { HUMAN_FACING_LESSON_TAG, LESSON_TRIGGERS } from './lesson-tags.js';
42
44
  import { AIS_MCP_INSTRUCTIONS } from './mcp-instructions.js';
43
45
  import { BOND_USAGE_LINE, HUMAN_HOWTO_TEXT, resolveInfoRequest } from './cli-info.js';
44
46
  import { describeStartupIdentity, findDuplicateServerNames, formatDuplicateServerWarning, formatStartupIdentityLine, setServerNameConflicts, setStartupIdentity, } from './startup-identity.js';
@@ -294,24 +296,23 @@ class BondPendingError extends Error {
294
296
  this.name = 'BondPendingError';
295
297
  }
296
298
  }
299
+ class DeviceApprovalRefusedError extends Error {
300
+ }
297
301
  /**
298
302
  * Wire the poll loop onto a freshly built flow. Shared by the mint path and
299
303
  * the resume path so a change to the poll/dead bookkeeping lands in one place.
300
304
  */
301
305
  function attachDeviceFlowPoll(flow, interval, reauth) {
302
- // flowRef points into the live flow object so auto-restart can update the
303
- // surfaced URL without the caller needing to restart the MCP process.
304
- const flowRef = flow;
305
- const poll = pollForToken(flow.device_code, interval, flow.agent_id, reauth, flowRef);
306
+ const poll = pollForToken(flow.device_code, interval, flow.agent_id, reauth, flow);
306
307
  flow.poll = poll;
307
- // Mark the flow dead as soon as its poll rejects so the next
308
- // `ensureCredentials` call starts a fresh flow. The `.catch` here is purely
309
- // for state-tracking — the original rejection is still observed by callers
310
- // racing `flow.poll`. We swallow on this branch to suppress unhandled
311
- // rejection warnings between rejection and the next ensureCredentials call.
308
+ // Track rejection and surface refused approvals even if the tool call has
309
+ // already returned a pending link. Callers racing flow.poll still receive
310
+ // the original rejection.
312
311
  poll.catch((error) => {
313
312
  flow.denied = error instanceof Error && error.message === DEVICE_DENIED_MESSAGE;
314
313
  flow.dead = true;
314
+ if (error instanceof DeviceApprovalRefusedError)
315
+ stderr(error.message);
315
316
  });
316
317
  return flow;
317
318
  }
@@ -372,26 +373,16 @@ function deviceAuthorizeBody() {
372
373
  }
373
374
  /** Fallback poll interval when a resumed record predates the stored field. */
374
375
  const DEFAULT_DEVICE_POLL_INTERVAL_S = 5;
375
- async function startDeviceFlow(priorProvisionalToken) {
376
+ async function startDeviceFlow(previousFlow = null) {
376
377
  emitTelemetry({ event: 'auth.device_flow.start' });
377
- // A caller that passes a prior provisional token has just watched its flow
378
- // die (expired, denied, timed out), so its code is spent — mint, never
379
- // resume. Only a process with no flow of its own looks on disk.
380
- const resumable = priorProvisionalToken ? null : loadPendingDeviceFlow();
381
- if (isResumableDeviceFlow(resumable)) {
382
- return resumeDeviceFlow(resumable);
378
+ const saved = loadPendingDeviceFlow();
379
+ const replaceSavedCode = previousFlow?.replaceCode && saved?.deviceCode === previousFlow.device_code;
380
+ if (!replaceSavedCode && isResumableDeviceFlow(saved)) {
381
+ return resumeDeviceFlow(saved);
383
382
  }
384
383
  stderr('Starting authentication...');
385
- // CORBOT-8F96A8EF: when this process has no in-flight flow of its own,
386
- // fall back to the provisional token left on disk by an earlier process.
387
- // Without this the token was only ever held in a module-level variable, so
388
- // every respawn of a stdio server signed in with nothing to present and
389
- // the server dutifully minted another agent. Sending it lets the server
390
- // reuse the SAME provisional agent (tryReuseProvisional); if the token is
391
- // stale or already bonded the server ignores it and mints, exactly as
392
- // before — so this can only reduce the number of agents, never break a
393
- // sign-in.
394
- const carriedToken = priorProvisionalToken ?? loadPendingDeviceFlow()?.provisionalToken;
384
+ // Carry the provisional proof when minting so the server can reuse the agent.
385
+ const carriedToken = saved?.provisionalToken ?? previousFlow?.provisional_token;
395
386
  const body = deviceAuthorizeBody();
396
387
  const authRes = (await aisPost('/v1/oauth/device/authorize', body, carriedToken));
397
388
  if (!authRes.success || !authRes.data) {
@@ -438,14 +429,26 @@ flowRef) {
438
429
  const pollIntervalMs = Math.max(interval, 5) * 1000;
439
430
  const handle = {
440
431
  device_code,
441
- verification_uri_complete: flowRef?.verification_uri_complete ?? '',
442
- user_code: flowRef?.user_code ?? '',
432
+ verification_uri_complete: flowRef.verification_uri_complete,
433
+ user_code: flowRef.user_code,
443
434
  };
444
435
  const pollResp = await runPollLoop(handle, {
445
- pollOnce: pollDeviceGrant,
436
+ pollOnce: async (code) => {
437
+ const response = await pollDeviceGrant(code);
438
+ flowRef.replaceCode = response.error === 'access_denied' ||
439
+ response.error === 'already_collected' || response.error === 'expired_token';
440
+ if (flowRef.replaceCode) {
441
+ const saved = loadPendingDeviceFlow();
442
+ if (saved?.deviceCode === code) {
443
+ // Keep the provisional proof for minting, including after a failed replacement.
444
+ savePendingDeviceFlow({ ...saved, codeExpiresAt: undefined });
445
+ }
446
+ }
447
+ return response;
448
+ },
446
449
  startNewFlow: async () => {
447
450
  const body = deviceAuthorizeBody();
448
- const authRes = (await aisPost('/v1/oauth/device/authorize', body, flowRef?.provisional_token));
451
+ const authRes = (await aisPost('/v1/oauth/device/authorize', body, flowRef.provisional_token));
449
452
  if (!authRes.success || !authRes.data) {
450
453
  throw new Error(`Re-authorization failed: ${authRes.error?.message ?? 'Unknown error'}`);
451
454
  }
@@ -458,11 +461,9 @@ flowRef) {
458
461
  // the new URL to the human without restarting the MCP process, and so
459
462
  // a THIRD expiry in the same flow re-sends the latest provisional
460
463
  // token rather than a stale, already-superseded one.
461
- if (flowRef) {
462
- flowRef.verification_uri_complete = newHandle.verification_uri_complete;
463
- flowRef.user_code = newHandle.user_code;
464
- flowRef.provisional_token = authRes.data.provisional_token;
465
- }
464
+ flowRef.verification_uri_complete = newHandle.verification_uri_complete;
465
+ flowRef.user_code = newHandle.user_code;
466
+ flowRef.provisional_token = authRes.data.provisional_token;
466
467
  // Keep the on-disk copy in step with the in-memory one (CORBOT-8F96A8EF).
467
468
  // A code that expires mid-flow issues a fresh provisional token; if the
468
469
  // process then dies, the stale token on disk would be rejected on the
@@ -490,15 +491,6 @@ flowRef) {
490
491
  },
491
492
  emitStderr: stderr,
492
493
  pollIntervalMs,
493
- }).catch((err) => {
494
- // DeviceFlowRestartedError is a recoverable restart — re-throw so the
495
- // caller (flow.poll handler) can treat it as a dead flow and start fresh.
496
- if (err instanceof DeviceFlowRestartedError) {
497
- throw new Error(`Device code expired and a new code was issued.\n` +
498
- `Visit: ${err.newVerificationUri}\n` +
499
- `Code: ${err.newUserCode}`);
500
- }
501
- throw err;
502
494
  });
503
495
  if (!pollResp.access_token) {
504
496
  throw new Error('Poll loop ended without an access token');
@@ -510,14 +502,16 @@ flowRef) {
510
502
  // token has no tenant either, and the reauth error is the one to surface.
511
503
  if (reauth && !bondClaims.agentId) {
512
504
  clearPendingDeviceFlow();
513
- throw new Error('Reauthentication failed: the approved token is missing an agent id');
505
+ throw new DeviceApprovalRefusedError('Reauthentication failed: the approved token is missing an agent id');
514
506
  }
515
507
  const bondedTenantId = bondClaims.tenantId;
516
508
  if (typeof bondedTenantId !== 'string' || bondedTenantId.trim().length === 0) {
517
509
  // Same cleanup as a finished bond: a rejected approval must not leave
518
510
  // the provisional token on disk for the next sign-in to reuse.
519
511
  clearPendingDeviceFlow();
520
- throw new Error('Approved access token is missing its bonded tenant');
512
+ throw new DeviceApprovalRefusedError(reauth
513
+ ? 'Reauthentication failed: the approved access token is missing its bonded tenant'
514
+ : 'Approved access token is missing its bonded tenant');
521
515
  }
522
516
  const expiresAt = new Date(Date.now() + (pollResp.expires_in ?? 604800) * 1000).toISOString();
523
517
  // Only the bond token's agent claim confirms an agent; the provisional flow
@@ -597,7 +591,9 @@ const tools = [
597
591
  {
598
592
  name: 'remember',
599
593
  description: 'Store a memory. Types: fact, event, lesson, context, goal, task. ' +
600
- 'Use expiresIn for short-lived status or per-tick notes so they drop out of recall after that many seconds. ' +
594
+ `When you learn a durable lesson, record it right away with type=lesson. Add a when:<trigger> tag when it applies at a specific decision point, e.g. when:${LESSON_TRIGGERS.turnStart}. ` +
595
+ `Add ${HUMAN_FACING_LESSON_TAG} only if the lesson changes how you work with your human. If the successful receipt has data.surfaceToHuman=true, briefly tell your human what will change. Keep other lesson writes quiet. ` +
596
+ 'Use expiresAt for a fixed expiry or expiresIn for a lifetime in seconds. Expired memories drop out of recall. ' +
601
597
  'Use rollingKey for a state that replaces itself (a handoff, a status line): each remember with the same key and type retires the previous one, so recall returns only the current version.' +
602
598
  BOND_LINK_NOTE,
603
599
  inputSchema: {
@@ -609,6 +605,7 @@ const tools = [
609
605
  tags: { type: 'array', items: { type: 'string' }, description: 'Optional tags to filter on later, e.g. ["work", "acme"]. At most 20; each 1-64 characters of a-z 0-9 . _ : - (stored lower-case). Tags are a filter, not a permission — use separate agents to wall off e.g. work from personal.' },
610
606
  supersedes: { type: 'string', description: 'Optional: the id of an older memory of yours that this one replaces (e.g. a lesson that turned out wrong). The old memory is kept but no longer returned by recall. Refused if that id is not one of your memories or is already superseded.' },
611
607
  expiresIn: { type: 'number', minimum: 60, maximum: 31536000, description: 'Optional lifetime in whole seconds (60–31536000). The memory is left out of recall after that time.' },
608
+ expiresAt: { type: 'string', format: 'date-time', description: 'Optional future ISO 8601 timestamp with timezone. Supply either expiresAt or expiresIn.' },
612
609
  rollingKey: { type: 'string', description: 'Optional key for a state that replaces itself, e.g. "next-session" or "lane-status". Each remember with the same key and type retires your earlier live memories with that key; they stay readable as history. 1-64 characters of a-z 0-9 . _ : - (stored lower-case). Not with supersedes.' },
613
610
  verbose: { type: 'boolean', description: 'Optional: true returns the whole stored memory, content included. Default: a short receipt with id, agentId, tier, createdAt, tokenEstimate and the supersedes result.' },
614
611
  },
@@ -636,14 +633,16 @@ const tools = [
636
633
  name: 'recall',
637
634
  description: "Search memories by natural language query. Set principalAgentId to search a DIFFERENT " +
638
635
  "agent's memories under a 'memory:read' grant from that agent's owner. " +
639
- "Each memory carries createdAt, updatedAt (its last edit), and tags. " +
636
+ "By default each memory carries id, content, createdAt, tags, type and truncated. " +
637
+ "Verbose replies include updatedAt (its last edit) and temporal.expiresAt when a memory has an expiry. " +
640
638
  "Pass orderBy='newest' with type or tags to get the newest matching memories first. " +
641
- "A memory longer than 2,000 characters comes back cut, with truncated=true and its contentLength; read it whole with memory_get and its id. " +
639
+ "A memory longer than 2,000 characters comes back cut, with truncated=true; read it whole with memory_get and its id. " +
642
640
  "Memories superseded by a newer one are left out; to list or page through every memory, " +
643
641
  "use the REST list route described in the aismemory README (cursor paging, sortBy=updatedAt, includeSuperseded=true)." + BOND_LINK_NOTE,
644
642
  inputSchema: {
645
643
  type: 'object',
646
644
  properties: {
645
+ fields: { type: 'string', enum: ['compact', 'verbose'], description: 'Compact by default. Choose verbose for additional memory metadata.' },
647
646
  query: { type: 'string', description: 'Search query' },
648
647
  limit: { type: 'number', description: `Max results (default ${DEFAULT_RECALL_LIMIT})` },
649
648
  type: { type: 'string', enum: ['fact', 'event', 'lesson', 'context', 'goal', 'task'], description: 'Filter by type' },
@@ -663,8 +662,9 @@ const tools = [
663
662
  inputSchema: {
664
663
  type: 'object',
665
664
  properties: {
665
+ fields: { type: 'string', enum: ['compact', 'verbose'], description: 'Compact by default. Choose verbose for additional memory metadata.' },
666
666
  id: { type: 'string', description: 'The memory id (UUID), as returned by recall or remember' },
667
- offset: { type: 'integer', minimum: 0, description: 'Character offset to start from. An answer carries at most 20,000 characters; when truncated is true, call again with the nextOffset it names.' },
667
+ offset: { type: 'integer', minimum: 0, description: 'Character offset to start from. An answer carries at most 20,000 characters; when truncated is true, call again with nextOffset (on the response envelope in compact mode and inside data in verbose mode).' },
668
668
  principalAgentId: { type: 'string', description: "Optional: the memory belongs to ANOTHER agent (its agent UUID). Requires that agent's owner to have granted you the 'memory:read' scope and that you share a tenant; otherwise the call is refused with 403." },
669
669
  },
670
670
  required: ['id'],
@@ -733,15 +733,15 @@ const tools = [
733
733
  'Every view is bounded: the default view budgets to 6000 tokens, and anything the ceiling cut is ' +
734
734
  "named in the response's receipt.omitted rather than dropped silently — goal titles are cut to 200 " +
735
735
  "characters with the goal's memory id in the payload, so the whole body is one memory-by-id fetch away. " +
736
- "Pass view='lean' for continuity only (last handoff first, recent memories) or view='bootstrap' " +
736
+ "Pass view='lean' for continuity only (last handoff and recent memories) or view='bootstrap' " +
737
737
  'for a cross-harness session start (adds goals and inbox). maxTokens sets the ceiling on any view.' + BOND_LINK_NOTE,
738
738
  inputSchema: {
739
739
  type: 'object',
740
740
  properties: {
741
741
  principalAgentId: { type: 'string', description: "Optional: search ANOTHER agent's memories instead of your own (its agent UUID). Requires that agent's owner to have granted you the 'memory:read' scope and that you share a tenant; otherwise the call is refused with 403. Read-only — your own identity and write access are unchanged." },
742
742
  memoriesLimit: { type: 'number', description: 'Number of memories to load (1-50, default 5). Lower values reduce context size. Governs recent memories only — on the full view that is a small share of the payload, so prefer view to bound the whole response.' },
743
- view: { type: 'string', enum: ['full', 'lean', 'bootstrap'], description: "Which projection to load. 'full' (default) is everything the stores hold, bounded to 6000 tokens. 'lean' is continuity only — last handoff first, then recent memories. 'bootstrap' is lean plus goals and inbox, for starting a session in another harness. All three honour maxTokens." },
744
- maxTokens: { type: 'number', description: 'Token ceiling (500-20000; default 6000 for full, 2000 for lean, 3000 for bootstrap). Content is evicted from the tail until the payload fits — assembled context sections, then facts, then goals, then recent memories on the full view — and each eviction is named in receipt.omitted. Identity, the operating layer and the last handoff are never dropped.' },
743
+ view: { type: 'string', enum: ['full', 'lean', 'bootstrap'], description: "Which projection to load. 'full' is the default. 'lean' loads the last handoff and recent memories. 'bootstrap' loads the last handoff, open orders, goals and inbox for starting a session in another harness. Lean and bootstrap shorten the handoff summary if that lets the newest memory or order fit." },
744
+ maxTokens: { type: 'number', description: 'Estimated token ceiling (500–20000). Full defaults to 6000 tokens. Lean and bootstrap default to content budgets of 2000 and 3000 tokens, respectively, plus the operating-layer allowance. An explicit ceiling counts the operating layer. Required sections can exceed the ceiling on their own. See receipt.omitted for budget cuts.' },
745
745
  openOrdersLimit: { type: 'number', description: 'Number of newest open task memories to include in bootstrap view (1-50; default 10).' },
746
746
  harness: { type: 'string', description: 'Your current harness for session-specific guidance: chatgpt, claude-code, claude-desktop, codex, cursor, or grokbot. Omit when unknown. Unrecognized names receive no harness guidance.' },
747
747
  contextWindowSize: { type: 'number', description: "Your model's context window in tokens (1000-10000000). The skills budget scales with it; omit for the server default." },
@@ -782,6 +782,7 @@ const tools = [
782
782
  description: 'With a workspace key: full agent ID (UUID), not a name. When signed in: agent name or ID.',
783
783
  },
784
784
  memoriesLimit: { type: 'integer', minimum: 1, maximum: 50, description: 'Number of memories to load (1-50). Omit to use the AIS default.' },
785
+ harness: { type: 'string', description: 'Your current harness for session-specific guidance: chatgpt, claude-code, claude-desktop, codex, cursor, or grokbot. Omit when unknown; it is filled in from the client when recognised.' },
785
786
  start: { type: 'boolean', description: "Default true: the answer carries a short readable start (the newest task memory tagged 'handoff', up to three lessons tagged 'when:turn-start', open orders; at most about 2,200 tokens with its notes). Each read counts as an API call. Pass false for counts and the receipt only." },
786
787
  },
787
788
  required: ['query'],
@@ -1061,12 +1062,16 @@ const HARNESS_NAMES = new Map([
1061
1062
  function normalizeHarness(name) {
1062
1063
  return name === undefined ? undefined : HARNESS_NAMES.get(name.trim().toLowerCase().replace(/\s+/g, '-'));
1063
1064
  }
1065
+ /** The session harness: AIS_HARNESS first, then the connected client's name; undefined when unknown. */
1066
+ function detectHarness(server) {
1067
+ return normalizeHarness(process.env.AIS_HARNESS) ?? normalizeHarness(server.getClientVersion()?.name);
1068
+ }
1064
1069
  function registerCallToolHandler(server, handler) {
1065
- const override = normalizeHarness(process.env.AIS_HARNESS);
1066
1070
  server.setRequestHandler(CallToolRequestSchema, (request) => {
1067
- if (request.params.name === 'full_context' && request.params.arguments?.harness === undefined) {
1071
+ const { name } = request.params;
1072
+ if ((name === 'full_context' || name === 'agent_load') && request.params.arguments?.harness === undefined) {
1068
1073
  // The SDK records clientInfo during initialize, after handler registration.
1069
- const harness = override ?? normalizeHarness(server.getClientVersion()?.name);
1074
+ const harness = detectHarness(server);
1070
1075
  if (harness !== undefined) {
1071
1076
  return handler({
1072
1077
  ...request,
@@ -1460,10 +1465,8 @@ async function main() {
1460
1465
  * has already approved, this returns the fresh credentials. If not, throws
1461
1466
  * BondPendingError so the calling tool returns the bond URL to the agent.
1462
1467
  *
1463
- * Recovery: if the previous flow's poll rejected (expired_token,
1464
- * access_denied, 30-min deadline, etc.), the dead flow is discarded and a
1465
- * new device flow is started inline — the user gets a fresh bond URL on
1466
- * the next tool call without having to restart the MCP process.
1468
+ * After a poll failure, the client retries the saved code while it is
1469
+ * usable and issues a fresh link when the code is terminal.
1467
1470
  */
1468
1471
  async function ensureCredentials(toolName) {
1469
1472
  const authenticated = await acquireCredentials();
@@ -1476,7 +1479,7 @@ async function main() {
1476
1479
  if (activeFlow && !activeFlow.dead)
1477
1480
  return activeFlow;
1478
1481
  const previousFlow = activeFlow;
1479
- startingFlow ??= startDeviceFlow(previousFlow?.provisional_token)
1482
+ startingFlow ??= startDeviceFlow(previousFlow)
1480
1483
  .then((flow) => {
1481
1484
  flow.replacesDenied = previousFlow?.denied === true;
1482
1485
  activeFlow = flow;
@@ -1564,12 +1567,10 @@ async function main() {
1564
1567
  new Promise((r) => setTimeout(() => r(sentinel), softTimeoutMs)),
1565
1568
  ]);
1566
1569
  }
1567
- catch (err) {
1568
- // Poll rejected (deadline / expired / denied). Start a fresh flow
1569
- // immediately and surface its new bond URL — no restart required.
1570
- // Always say WHY the old flow died: a silent discard here hid three
1571
- // weeks of broken cold-start bonding (CORBOT-9CE03C6E).
1572
- stderr(`Device flow discarded (${err instanceof Error ? err.message : String(err)}); starting a fresh one.`);
1570
+ catch (error) {
1571
+ if (error instanceof DeviceApprovalRefusedError)
1572
+ throw error;
1573
+ stderr('Device polling stopped. Checking whether the bond link can be reused.');
1573
1574
  const replacement = await getDeviceFlow();
1574
1575
  throw new BondPendingError(replacement.verification_uri_complete, replacement.user_code, replacement.replacesDenied);
1575
1576
  }
@@ -1607,7 +1608,7 @@ async function main() {
1607
1608
  (!sessionIdentity && !process.env['AIS_AGENT_NAME']))
1608
1609
  return;
1609
1610
  try {
1610
- agentContext = await hydrateIdentity(AIS_URL, c.agentId, c.token);
1611
+ agentContext = await hydrateIdentity(AIS_URL, c.agentId, c.token, undefined, detectHarness(server));
1611
1612
  if (agentContext) {
1612
1613
  stderr(`Agent loaded: ${agentContext.identity.name} (${agentContext.recentMemories.length} memories, ${agentContext.goals.length} goals)`);
1613
1614
  server.notification({ method: 'notifications/prompts/list_changed' });
@@ -1641,7 +1642,8 @@ async function main() {
1641
1642
  stderr('Session handoff saved');
1642
1643
  }, () => verifyConfirmedIdentityForAutoHandoff(sessionIdentity, c.agentId, () => aisGet(`/v1/agents/${c.agentId}`, c.token), { credentialKey: identityCredentialFingerprint('oauth-bearer', c.token) }));
1643
1644
  }
1644
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
1645
+ // CORBOT-86A96AFB: library_search / library_fetch only when ACCOUNT_LIBRARY_MCP_ENABLED=true.
1646
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: withLibraryTools(tools) }));
1645
1647
  server.setRequestHandler(ListPromptsRequestSchema, async () => ({
1646
1648
  prompts: agentContext
1647
1649
  ? [{ name: 'agent-identity', description: 'Active AIS agent identity, personality, and context' }]
@@ -0,0 +1,16 @@
1
+ import { z } from 'zod';
2
+ export declare const LESSON_TRIGGERS: readonly ["turn-start", "merge", "push", "db-change", "spend", "ask-human", "claim-ticket", "write-plan", "long-run"];
3
+ declare const lessonsSchema: z.ZodArray<z.ZodObject<{
4
+ id: z.ZodString;
5
+ content: z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>;
6
+ }, z.core.$strip>>;
7
+ interface LessonAdviceScope {
8
+ cacheDir: string;
9
+ sessionId: string;
10
+ aisUrl: string;
11
+ agentId: string;
12
+ credentialKey: string;
13
+ }
14
+ /** Own active lessons only. Cache successful reads, including an empty list. */
15
+ export declare function lookupLessonAdvice(trigger: string, scope: LessonAdviceScope, get: (path: string) => Promise<unknown>): Promise<z.output<typeof lessonsSchema>>;
16
+ export {};