@koalaauto/agentchannel 3.97.0 → 3.97.2

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.
@@ -0,0 +1,33 @@
1
+ import type { ArtifactOut } from '../client.js';
2
+ export declare const ARTIFACTS_MAX = 3;
3
+ /** Characters of page text one run is given, over all its artifacts (a 25-episode script page on prod is 40k). */
4
+ export declare const ARTIFACT_TEXT_BUDGET = 60000;
5
+ /** A page larger than this is not fetched (pages with embedded video run to tens of MB; its text would be a small part). */
6
+ export declare const ARTIFACT_BYTES_MAX: number;
7
+ /** An artifact named in a run's material, as the run is given it; one that could not be read says why. */
8
+ export interface LinkedArtifact {
9
+ ref: string;
10
+ title?: string;
11
+ version?: number;
12
+ owner?: string;
13
+ /** the whole length of the page's text; `text` stops at the budget */
14
+ chars?: number;
15
+ note?: string;
16
+ /** what the page shows that is not text, and so is not here: "27 images, 1 video" */
17
+ not_included?: string;
18
+ text?: string;
19
+ error?: string;
20
+ }
21
+ /** The distinct artifacts named in `texts` ("A-12", an /artifact/A-12 link), first seen first. */
22
+ export declare function artifactRefs(texts: (string | undefined | null)[]): string[];
23
+ /** The text a person reads on an HTML page, and a count of what it shows that is not text. */
24
+ export declare function pageText(html: string): {
25
+ text: string;
26
+ notIncluded: string;
27
+ };
28
+ export interface ArtifactReader {
29
+ get: (ref: string) => Promise<ArtifactOut>;
30
+ html: (a: ArtifactOut) => Promise<string>;
31
+ }
32
+ /** Read up to ARTIFACTS_MAX of the artifacts `texts` name (the latest version of each), within one text budget for the run. */
33
+ export declare function linkedArtifacts(texts: (string | undefined | null)[], read: ArtifactReader | undefined): Promise<LinkedArtifact[]>;
@@ -0,0 +1,73 @@
1
+ export const ARTIFACTS_MAX = 3;
2
+ /** Characters of page text one run is given, over all its artifacts (a 25-episode script page on prod is 40k). */
3
+ export const ARTIFACT_TEXT_BUDGET = 60_000;
4
+ /** A page larger than this is not fetched (pages with embedded video run to tens of MB; its text would be a small part). */
5
+ export const ARTIFACT_BYTES_MAX = 32 * 1024 * 1024;
6
+ // the hub's own pattern (worker domain/artifacts.ts REF_RE): A-12, not DATA-12 or A-12-b
7
+ const REF = /(?<![\w-])A-(\d{1,7})(?![\w-])/g;
8
+ /** The distinct artifacts named in `texts` ("A-12", an /artifact/A-12 link), first seen first. */
9
+ export function artifactRefs(texts) {
10
+ const out = [];
11
+ for (const t of texts)
12
+ for (const m of (t ?? '').matchAll(REF)) {
13
+ const ref = `A-${parseInt(m[1], 10)}`;
14
+ if (!out.includes(ref))
15
+ out.push(ref);
16
+ }
17
+ return out;
18
+ }
19
+ const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
20
+ const NOT_TEXT = [[/<img\b/gi, 'image'], [/<video\b/gi, 'video'], [/<audio\b/gi, 'audio clip'], [/<(?:svg|canvas)\b/gi, 'drawing or chart'], [/<iframe\b/gi, 'embedded page']];
21
+ /** The text a person reads on an HTML page, and a count of what it shows that is not text. */
22
+ export function pageText(html) {
23
+ const counts = NOT_TEXT.map(([re, name]) => [html.match(re)?.length ?? 0, name]).filter(([n]) => n > 0);
24
+ const text = html
25
+ .replace(/<!--[\s\S]*?-->/g, ' ')
26
+ .replace(/<(script|style|svg|template|noscript)\b[\s\S]*?<\/\1\s*>/gi, ' ')
27
+ .replace(/<(?:br|hr)\b[^>]*>|<\/(?:p|div|section|article|header|footer|li|tr|table|h[1-6]|blockquote|pre|title)\s*>/gi, '\n')
28
+ .replace(/<\/(?:td|th)\s*>/gi, ' | ')
29
+ .replace(/<[^>]*>/g, ' ')
30
+ .replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n) || 32))
31
+ .replace(/&#x([0-9a-f]+);/gi, (_, n) => String.fromCodePoint(parseInt(n, 16) || 32))
32
+ .replace(/&([a-z]+);/gi, (m, n) => ENTITIES[n.toLowerCase()] ?? m)
33
+ .replace(/[ \t\r\f\v]+/g, ' ')
34
+ .replace(/ ?\n ?/g, '\n')
35
+ .replace(/\n{2,}/g, '\n')
36
+ .trim();
37
+ return { text, notIncluded: counts.map(([n, name]) => `${n} ${name}${n > 1 && !name.includes(' or ') ? 's' : ''}`).join(', ') };
38
+ }
39
+ /** Read up to ARTIFACTS_MAX of the artifacts `texts` name (the latest version of each), within one text budget for the run. */
40
+ export async function linkedArtifacts(texts, read) {
41
+ if (!read)
42
+ return [];
43
+ const refs = artifactRefs(texts);
44
+ const out = [];
45
+ let left = ARTIFACT_TEXT_BUDGET;
46
+ for (const ref of refs.slice(0, ARTIFACTS_MAX)) {
47
+ try {
48
+ const a = await read.get(ref);
49
+ const head = { ref, title: a.title, version: a.version, ...(a.owner_name ? { owner: a.owner_name } : {}) };
50
+ const size = (a.versions ?? []).find((v) => v.version === a.version)?.size ?? 0;
51
+ if (size > ARTIFACT_BYTES_MAX) {
52
+ out.push({ ...head, error: `not read: the page is ${Math.round(size / 1024 / 1024)} MB (pages over ${ARTIFACT_BYTES_MAX / 1024 / 1024} MB are not read; it is mostly embedded media)` });
53
+ continue;
54
+ }
55
+ const { text, notIncluded } = pageText(await read.html(a));
56
+ const given = text.slice(0, left);
57
+ left -= given.length;
58
+ out.push({
59
+ ...head,
60
+ chars: text.length,
61
+ ...(given.length < text.length ? { note: given.length ? `text cut off: first ${given.length.toLocaleString('en')} of ${text.length.toLocaleString('en')} characters` : `text not given: the ${ARTIFACT_TEXT_BUDGET.toLocaleString('en')} characters one run is given were used by the artifacts before it` } : {}),
62
+ ...(notIncluded ? { not_included: notIncluded } : {}),
63
+ text: given,
64
+ });
65
+ }
66
+ catch (e) {
67
+ out.push({ ref, error: String(e?.message ?? e).slice(0, 300) });
68
+ }
69
+ }
70
+ for (const ref of refs.slice(ARTIFACTS_MAX))
71
+ out.push({ ref, error: `not read: at most ${ARTIFACTS_MAX} artifacts are read for one run` });
72
+ return out;
73
+ }
@@ -0,0 +1,70 @@
1
+ import { type Agent } from '../client.js';
2
+ import type { SandboxStatus } from '../sandboxcheck.js';
3
+ import type { RunnerOptions } from './runner.js';
4
+ /** How often the runner asks its runtime which models it offers. */
5
+ export declare const MODELS_EVERY_MS: number;
6
+ /** What the reports need of the runner they speak for. */
7
+ export interface ReportsHost {
8
+ log(s: string): void;
9
+ authFailed(where: string, e?: unknown): void;
10
+ ensureMe(): Promise<Agent>;
11
+ /** the agent's record as last read, if any */
12
+ me(): Agent | undefined;
13
+ /** the run works elsewhere (a cloud sandbox): nothing of this machine reaches it */
14
+ readonly cloud: boolean;
15
+ /** short runs return JSON by a schema */
16
+ readonly structured: boolean;
17
+ }
18
+ export declare class RunnerReports {
19
+ private o;
20
+ private h;
21
+ constructor(o: RunnerOptions & Required<Pick<RunnerOptions, 'perm'>>, h: ReportsHost);
22
+ /** what the hub was last told keeps this runner from working (a JSON key) */
23
+ private setupReported?;
24
+ /** Tell the hub what keeps this runner from working, when that changed: a failed check first, else an account that cannot run. */
25
+ reportSetup(st: SandboxStatus | undefined): Promise<void>;
26
+ /** Tell the hub which repo names this runner knows, so a task for another repo is refused when it is sent. Tried on every
27
+ * poll until the hub has it: a hub that was unreachable at start would otherwise keep the previous list until a restart. */
28
+ private reposReported;
29
+ reportRepos(): Promise<void>;
30
+ private reposLogged;
31
+ /** An agent with no profile yet gets a first one, once: a short read-only run on a light model reads the repositories it works in
32
+ * and writes a sentence or two. The hub keeps it only while the profile is empty; the weekly refresh (the system agent, from what the
33
+ * agent did) rewrites it after. The description is the owner's and is never written here. Tried again at the next start when it
34
+ * could not be had. */
35
+ private describeDone;
36
+ private describeBusy;
37
+ private describeTries;
38
+ private describeNextAt;
39
+ describeAgent(): Promise<void>;
40
+ /** Tell the hub how this runner runs tasks (its --perm, the tool, the names it passes with --pass-env), once, so the agent's
41
+ * owner sees on its page what a task sent to it can reach. Tried on every poll until the hub has it; an older hub (404) is left alone. */
42
+ private runnerReported;
43
+ /** the capabilities last told to the hub (decisions §34, §38): an edit of the file is reported again on the next poll */
44
+ private capsReported;
45
+ reportRunner(): Promise<void>;
46
+ /**
47
+ * Tell the hub which models the runtime offers here and which one a run uses when none is picked (the agent's settings
48
+ * page lists them): when the runner starts, again a day later (a login or the tool's catalog changes), and at once after
49
+ * a run's model was rejected. Asked with the environment a run gets, so the list is what this agent's login can use.
50
+ */
51
+ private modelsAt;
52
+ private modelsBusy;
53
+ /** set when a run's model was rejected: the list on the hub is out of date */
54
+ modelsStale: boolean;
55
+ /** an older hub without /me/models, or a runtime that cannot list: asked no more */
56
+ private modelsOff;
57
+ private modelsLogged;
58
+ reportModels(): Promise<void>;
59
+ /** the project memory index last told to the hub, and when the file was last looked at */
60
+ private projectMemoryReported;
61
+ private projectMemoryCheckedAt;
62
+ /**
63
+ * Tell the hub what this agent knows about its project: the index of the owner's memory for it on this machine (one line per
64
+ * note, never the notes). The owner's Yoda reads it, so it knows what each of its parts knows (primary-agent-design §11.15).
65
+ * Looked at every few minutes, sent when it changed. Not for a team agent (no person) or a cloud run (no machine).
66
+ */
67
+ reportProjectMemory(now?: number): Promise<void>;
68
+ }
69
+ /** The model's text as a profile: its first paragraph, without markdown marks or wrapping quotes, at most 300 characters. */
70
+ export declare function cleanDescription(raw: string): string;
@@ -0,0 +1,299 @@
1
+ // What a runner tells the hub about itself, apart from the work it does: what keeps it from working, the repositories it knows,
2
+ // how it runs tasks and what it can reach, the models its runtime offers, a first profile, the index of its project memory.
3
+ // Each is sent when it changed (or once), tried again while the hub does not have it, and left alone on an older hub (404).
4
+ // The runner calls them from its poll loop (runner.ts); nothing here takes or runs a task.
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { isRuntime, runRefusal } from '../adapters/spec.js';
8
+ import { capsPath, loadCaps } from '../caps.js';
9
+ import { HubError } from '../client.js';
10
+ import { inheritedEnv } from '../env.js';
11
+ import { summarizeRuntimeError } from '../envcheck.js';
12
+ import { memoryIndex, ownerMemoryDir } from './context.js';
13
+ import { prepareAgentHome, realHomeOf, secretPaths } from './home.js';
14
+ /** How often the runner asks its runtime which models it offers. */
15
+ export const MODELS_EVERY_MS = 24 * 60 * 60_000;
16
+ /** How often the runner looks whether the project's memory index changed (it reports it to the hub when it did). */
17
+ const PROJECT_MEMORY_EVERY_MS = 5 * 60_000;
18
+ const is401 = (e) => e instanceof HubError && e.status === 401;
19
+ export class RunnerReports {
20
+ o;
21
+ h;
22
+ constructor(o, h) {
23
+ this.o = o;
24
+ this.h = h;
25
+ }
26
+ /** what the hub was last told keeps this runner from working (a JSON key) */
27
+ setupReported;
28
+ /** Tell the hub what keeps this runner from working, when that changed: a failed check first, else an account that cannot run. */
29
+ async reportSetup(st) {
30
+ const report = !st ? null : { tool: st.tool, problem: st.problem ?? 'failed', ...(st.detail ? { detail: st.detail } : {}), ...(st.fix ? { fix: st.fix } : {}) };
31
+ const key = JSON.stringify(report);
32
+ if (key !== this.setupReported && this.o.client.reportSetup) {
33
+ try {
34
+ await this.o.client.reportSetup(report);
35
+ this.setupReported = key;
36
+ }
37
+ catch (e) {
38
+ if (is401(e))
39
+ this.h.authFailed('setup', e);
40
+ // an older hub without /me/setup: the log above is all there is
41
+ else if (e instanceof HubError && e.status === 404)
42
+ this.setupReported = key;
43
+ else
44
+ this.h.log(`setup report: ${e?.message ?? e}`);
45
+ }
46
+ }
47
+ }
48
+ /** Tell the hub which repo names this runner knows, so a task for another repo is refused when it is sent. Tried on every
49
+ * poll until the hub has it: a hub that was unreachable at start would otherwise keep the previous list until a restart. */
50
+ reposReported = false;
51
+ async reportRepos() {
52
+ if (this.reposReported)
53
+ return;
54
+ // an empty list is reported too: the hub then refuses a task that names a repo, and forgets names an earlier start gave
55
+ const names = await this.o.workspace.repoNames?.();
56
+ if (!names || !this.o.client.reportRepos) {
57
+ this.reposReported = true;
58
+ return;
59
+ }
60
+ try {
61
+ await this.o.client.reportRepos(names, await this.o.workspace.repoRemotes?.().catch(() => undefined));
62
+ this.reposReported = true;
63
+ }
64
+ catch (e) {
65
+ // an older hub without /me/repos: nothing is checked there, which is how it was
66
+ if (e instanceof HubError && e.status === 404)
67
+ this.reposReported = true;
68
+ else if (!this.reposLogged) {
69
+ this.reposLogged = true;
70
+ this.h.log(`repos report: ${e?.message ?? e} (trying again with the next poll)`);
71
+ }
72
+ }
73
+ }
74
+ reposLogged = false;
75
+ /** An agent with no profile yet gets a first one, once: a short read-only run on a light model reads the repositories it works in
76
+ * and writes a sentence or two. The hub keeps it only while the profile is empty; the weekly refresh (the system agent, from what the
77
+ * agent did) rewrites it after. The description is the owner's and is never written here. Tried again at the next start when it
78
+ * could not be had. */
79
+ describeDone = false;
80
+ describeBusy = false;
81
+ describeTries = 0;
82
+ describeNextAt = 0;
83
+ async describeAgent() {
84
+ const { adapter, client, workspace } = this.o;
85
+ if (this.describeDone || this.describeBusy || Date.now() < this.describeNextAt || this.h.cloud || !client.reportProfile || !workspace.repoDirs)
86
+ return;
87
+ this.describeBusy = true;
88
+ try {
89
+ const me = await this.h.ensureMe();
90
+ if (me.role === 'system' || String(me.profile ?? '').trim()) {
91
+ this.describeDone = true;
92
+ return;
93
+ }
94
+ const dirs = Object.entries(await workspace.repoDirs()).slice(0, 4);
95
+ if (!dirs.length)
96
+ return;
97
+ const baseEnv = this.o.baseEnv ?? process.env;
98
+ const realHome = realHomeOf(baseEnv);
99
+ const { env } = prepareAgentHome(this.o.agentHomesDir ?? join(tmpdir(), 'ach-homes'), me.name, 'describe', realHome, baseEnv.CODEX_HOME || undefined);
100
+ const run = async (pick) => {
101
+ const ctl = new AbortController();
102
+ const timer = setTimeout(() => ctl.abort(), 3 * 60_000);
103
+ try {
104
+ const refused = runRefusal(adapter.spec, { perm: 'read', ...(Array.isArray(me.net_allow) ? { netAllow: me.net_allow } : {}) });
105
+ if (refused)
106
+ return { ok: false, finalText: '', error: `not run: ${refused}` };
107
+ return await adapter.run({
108
+ ...(pick ? { model: pick.model, effort: pick.effort } : {}),
109
+ prompt: describePrompt(me.name, dirs, me.lang),
110
+ cwd: dirs[0][1],
111
+ perm: 'read',
112
+ mode: 'answer',
113
+ env: { ...inheritedEnv(baseEnv, this.o.passEnv), ...env },
114
+ signal: ctl.signal,
115
+ hub: this.o.hub,
116
+ denyReadPaths: secretPaths(this.o.home),
117
+ ...(realHome ? { realHome } : {}),
118
+ readRoots: dirs.map(([, d]) => d),
119
+ ...(env.TMPDIR ? { tmpDir: env.TMPDIR } : {}),
120
+ ...(Array.isArray(me.net_allow) ? { netAllow: me.net_allow } : {}),
121
+ ...(adapter.spec.budget ? { maxBudgetUsd: 0.05 } : {}),
122
+ ...(this.h.structured ? { outputSchema: DESCRIBE_SCHEMA } : {}),
123
+ onEvent: () => { },
124
+ });
125
+ }
126
+ finally {
127
+ clearTimeout(timer);
128
+ }
129
+ };
130
+ // the light model where the runtime has one; a model the account cannot use falls back to the runtime's default
131
+ const light = adapter.spec.lightModel;
132
+ let r = await run(light);
133
+ if (!r.ok && light)
134
+ r = await run(undefined);
135
+ const text = cleanDescription(r.finalText);
136
+ if (!r.ok || !text)
137
+ throw new Error(r.error ? summarizeRuntimeError(r.error).slice(0, 160) : 'no profile came back');
138
+ await client.reportProfile(text);
139
+ this.describeDone = true;
140
+ this.h.log(`profile: ${text.slice(0, 120)}`);
141
+ }
142
+ catch (e) {
143
+ // an older hub without /me/profile (404) says nothing and is left alone; any other failure (a hub or network that was not
144
+ // reachable while many runners restarted at once, a model that said nothing) is tried again, three times in all per start
145
+ if (e instanceof HubError && e.status === 404)
146
+ this.describeDone = true;
147
+ else if (++this.describeTries >= 3) {
148
+ this.describeDone = true;
149
+ this.h.log(`profile: ${String(e?.message ?? e).slice(0, 200)} (gave up until the next start)`);
150
+ }
151
+ else {
152
+ this.describeNextAt = Date.now() + (this.o.describeRetryMs ?? 5 * 60_000);
153
+ this.h.log(`profile: ${String(e?.message ?? e).slice(0, 200)} (trying again in ${Math.round((this.o.describeRetryMs ?? 5 * 60_000) / 60_000)} min)`);
154
+ }
155
+ }
156
+ finally {
157
+ this.describeBusy = false;
158
+ }
159
+ }
160
+ /** Tell the hub how this runner runs tasks (its --perm, the tool, the names it passes with --pass-env), once, so the agent's
161
+ * owner sees on its page what a task sent to it can reach. Tried on every poll until the hub has it; an older hub (404) is left alone. */
162
+ runnerReported = false;
163
+ /** the capabilities last told to the hub (decisions §34, §38): an edit of the file is reported again on the next poll */
164
+ capsReported = '';
165
+ async reportRunner() {
166
+ if (!this.o.client.reportRunner)
167
+ return;
168
+ // the names and descriptions only, never the commands: teammates see them in the agent directory
169
+ // decisions §38: MCP servers with their tool names, skills by name; never a URL, a command or a credential
170
+ const decl = this.h.cloud ? undefined : loadCaps(this.o.capsFile ?? capsPath(this.o.home));
171
+ const capabilities = decl
172
+ ? [
173
+ ...decl.caps.map((c) => ({ kind: 'command', name: c.name, description: c.description.slice(0, 300) })),
174
+ ...decl.mcp.map((m) => ({ kind: 'mcp', name: m.name, description: m.description.slice(0, 300), tools: m.tools.slice(0, 50) })),
175
+ ...decl.skills.map((k) => ({ kind: 'skill', name: k.name, description: k.description.slice(0, 300) })),
176
+ ].slice(0, 50)
177
+ : [];
178
+ const sig = JSON.stringify(capabilities);
179
+ if (this.runnerReported && sig === this.capsReported)
180
+ return;
181
+ const runtime = this.o.adapter.name;
182
+ if (!isRuntime(runtime)) {
183
+ this.runnerReported = true;
184
+ this.capsReported = sig;
185
+ return;
186
+ }
187
+ try {
188
+ // review: this runner knows the owner's review step (a task it finishes may wait in awaiting_review, decisions §36)
189
+ await this.o.client.reportRunner({ perm: this.o.perm, runtime, pass_env: [...new Set(this.o.passEnv ?? [])], capabilities, review: true, ...(this.o.startInfo ?? {}) });
190
+ this.runnerReported = true;
191
+ this.capsReported = sig;
192
+ }
193
+ catch (e) {
194
+ if (e instanceof HubError && e.status === 404) {
195
+ this.runnerReported = true;
196
+ this.capsReported = sig;
197
+ }
198
+ }
199
+ }
200
+ /**
201
+ * Tell the hub which models the runtime offers here and which one a run uses when none is picked (the agent's settings
202
+ * page lists them): when the runner starts, again a day later (a login or the tool's catalog changes), and at once after
203
+ * a run's model was rejected. Asked with the environment a run gets, so the list is what this agent's login can use.
204
+ */
205
+ modelsAt = 0;
206
+ modelsBusy = false;
207
+ /** set when a run's model was rejected: the list on the hub is out of date */
208
+ modelsStale = false;
209
+ /** an older hub without /me/models, or a runtime that cannot list: asked no more */
210
+ modelsOff = false;
211
+ modelsLogged = '';
212
+ async reportModels() {
213
+ const adapter = this.o.adapter;
214
+ if (this.modelsOff || this.modelsBusy || !adapter.listModels || !this.o.client.reportModels)
215
+ return;
216
+ if (this.modelsAt && !this.modelsStale && Date.now() - this.modelsAt < MODELS_EVERY_MS)
217
+ return;
218
+ this.modelsBusy = true;
219
+ this.modelsAt = Date.now();
220
+ this.modelsStale = false;
221
+ try {
222
+ const me = await this.h.ensureMe();
223
+ const baseEnv = this.o.baseEnv ?? process.env;
224
+ const realHome = realHomeOf(baseEnv);
225
+ const { home, env } = prepareAgentHome(this.o.agentHomesDir ?? join(tmpdir(), 'ach-homes'), me.name, 'model-list', realHome, baseEnv.CODEX_HOME || undefined);
226
+ const list = await adapter.listModels({ env: { ...inheritedEnv(baseEnv, this.o.passEnv), ...env }, cwd: home, ...(realHome ? { realHome } : {}) });
227
+ await this.o.client.reportModels({ runtime: adapter.name, ...list });
228
+ this.modelsLogged = '';
229
+ }
230
+ catch (e) {
231
+ if (e instanceof HubError && e.status === 404)
232
+ this.modelsOff = true;
233
+ const msg = String(e?.message ?? e).slice(0, 300);
234
+ // a list that cannot be had is not worth a line every day: said once until it changes
235
+ if (!this.modelsOff && msg !== this.modelsLogged) {
236
+ this.modelsLogged = msg;
237
+ this.h.log(`model list: ${msg} (trying again in a day)`);
238
+ }
239
+ }
240
+ finally {
241
+ this.modelsBusy = false;
242
+ }
243
+ }
244
+ /** the project memory index last told to the hub, and when the file was last looked at */
245
+ projectMemoryReported;
246
+ projectMemoryCheckedAt = 0;
247
+ /**
248
+ * Tell the hub what this agent knows about its project: the index of the owner's memory for it on this machine (one line per
249
+ * note, never the notes). The owner's Yoda reads it, so it knows what each of its parts knows (primary-agent-design §11.15).
250
+ * Looked at every few minutes, sent when it changed. Not for a team agent (no person) or a cloud run (no machine).
251
+ */
252
+ async reportProjectMemory(now = Date.now()) {
253
+ if (!this.o.client.reportProjectMemory || this.h.cloud || !this.h.me() || this.h.me()?.kind === 'team')
254
+ return;
255
+ if (now - this.projectMemoryCheckedAt < PROJECT_MEMORY_EVERY_MS)
256
+ return;
257
+ this.projectMemoryCheckedAt = now;
258
+ const dir = ownerMemoryDir(this.o.dir, realHomeOf(this.o.baseEnv ?? process.env));
259
+ const index = dir ? memoryIndex(dir) : '';
260
+ if (index === this.projectMemoryReported || (!index && this.projectMemoryReported === undefined))
261
+ return;
262
+ try {
263
+ await this.o.client.reportProjectMemory(index);
264
+ this.projectMemoryReported = index;
265
+ }
266
+ catch (e) {
267
+ // an older hub has no such route: say nothing more
268
+ if (e instanceof HubError && (e.status === 404 || e.status === 400))
269
+ this.projectMemoryReported = index;
270
+ }
271
+ }
272
+ }
273
+ /** The light model that writes an agent's first profile, per runtime (none listed: the runtime's default). A runtime that does not
274
+ * take it runs the default instead. */
275
+ const DESCRIBE_SCHEMA = { type: 'object', properties: { profile: { type: 'string' } }, required: ['profile'], additionalProperties: false };
276
+ function describePrompt(name, dirs, lang) {
277
+ const where = dirs.map(([n, d]) => `- ${n}: ${d}`).join('\n');
278
+ return [
279
+ `You are writing the one-paragraph profile of the agent "${name}" for the team directory. Teammates and other agents read it to decide whether to send this agent a piece of work.`,
280
+ `The agent works in these repositories (read-only for you; start with README, CLAUDE.md, AGENTS.md and the top-level layout, do not read everything):`,
281
+ where,
282
+ `Write one or two sentences in ${lang === 'en' ? 'English' : 'Chinese'}: what the repository is for and what kind of work belongs with this agent. Be specific (name the main parts or systems), not generic. At most 160 characters. Plain text only: no markdown, no quotes, no list, no preface.`,
283
+ 'Answer with the profile text only.',
284
+ ].filter(Boolean).join('\n\n');
285
+ }
286
+ /** The model's text as a profile: its first paragraph, without markdown marks or wrapping quotes, at most 300 characters. */
287
+ export function cleanDescription(raw) {
288
+ let t = String(raw ?? '').trim();
289
+ try {
290
+ const j = JSON.parse(t);
291
+ if (j && typeof j.profile === 'string')
292
+ t = j.profile;
293
+ }
294
+ catch {
295
+ /* plain text */
296
+ }
297
+ t = t.split(/\n\s*\n/)[0].replace(/\*\*|__|[`*]|^\s*[#>]+\s*/gm, '').replace(/\s+/g, ' ').trim().replace(/^["'“”「」]+|["'“”「」]+$/g, '').trim();
298
+ return t.slice(0, 300);
299
+ }