@oyasmi/pipiclaw 0.9.3-beta.3 → 0.9.3-beta.4
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/dist/agent/channel-runner.d.ts +4 -18
- package/dist/agent/channel-runner.js +25 -120
- package/dist/agent/context-budget.js +1 -1
- package/dist/agent/job-manager.d.ts +11 -17
- package/dist/agent/job-manager.js +76 -65
- package/dist/agent/prompt/builder.js +1 -17
- package/dist/agent/prompt/manifest.d.ts +0 -1
- package/dist/agent/prompt/manifest.js +2 -2
- package/dist/agent/prompt/sections.js +0 -9
- package/dist/agent/prompt/types.d.ts +2 -18
- package/dist/agent/prompt/types.js +1 -1
- package/dist/agent/runner-factory.d.ts +4 -0
- package/dist/agent/session-adapter.d.ts +19 -0
- package/dist/agent/session-adapter.js +77 -0
- package/dist/app-services.d.ts +18 -0
- package/dist/app-services.js +43 -0
- package/dist/{runtime → events}/events.d.ts +1 -1
- package/dist/memory/journal.js +1 -1
- package/dist/memory/maintenance-gates.d.ts +0 -3
- package/dist/memory/maintenance-gates.js +2 -2
- package/dist/memory/maintenance-migration.d.ts +5 -0
- package/dist/memory/maintenance-migration.js +91 -0
- package/dist/memory/maintenance-state.js +5 -44
- package/dist/memory/migrate.js +1 -1
- package/dist/memory/reflect-job.d.ts +1 -9
- package/dist/memory/reflect-job.js +1 -3
- package/dist/memory/reflect.js +1 -1
- package/dist/memory/session-corpus.js +1 -1
- package/dist/memory/store.js +1 -1
- package/dist/models/auth-cli.js +1 -1
- package/dist/runtime/bootstrap.d.ts +5 -15
- package/dist/runtime/bootstrap.js +32 -56
- package/dist/runtime/subagent-commands.d.ts +2 -1
- package/dist/runtime/subagent-commands.js +10 -12
- package/dist/runtime/task-wake.d.ts +4 -5
- package/dist/runtime/task-wake.js +2 -12
- package/dist/security/types.d.ts +7 -0
- package/dist/security/types.js +16 -1
- package/dist/settings.d.ts +8 -0
- package/dist/settings.js +24 -1
- package/dist/shared/exact-keys.d.ts +13 -0
- package/dist/shared/exact-keys.js +1 -0
- package/dist/shared/format.d.ts +20 -0
- package/dist/shared/format.js +64 -0
- package/dist/shared/{fs-utils.d.ts → os.d.ts} +6 -0
- package/dist/shared/{fs-utils.js → os.js} +8 -0
- package/dist/subagents/discovery.d.ts +16 -3
- package/dist/subagents/discovery.js +9 -7
- package/dist/subagents/external/run.d.ts +2 -1
- package/dist/subagents/external/run.js +1 -2
- package/dist/subagents/external/settlement.js +10 -5
- package/dist/subagents/format.d.ts +1 -1
- package/dist/subagents/format.js +1 -1
- package/dist/subagents/runs.d.ts +13 -12
- package/dist/subagents/runs.js +108 -89
- package/dist/subagents/tool.d.ts +7 -7
- package/dist/subagents/tool.js +11 -11
- package/dist/tasks/brief.js +1 -0
- package/dist/tools/command-optimizer.js +1 -1
- package/dist/tools/config.d.ts +7 -0
- package/dist/tools/config.js +16 -1
- package/dist/tools/event-manage.d.ts +1 -1
- package/dist/tools/event-manage.js +3 -3
- package/dist/tools/grep.js +1 -1
- package/dist/tools/index.d.ts +4 -0
- package/dist/tools/index.js +4 -2
- package/dist/tools/job.js +1 -1
- package/dist/tools/read.js +1 -1
- package/dist/tools/registry.d.ts +3 -3
- package/dist/tools/registry.js +18 -56
- package/dist/tools/skill.js +1 -1
- package/dist/tools/subagent-manage.d.ts +2 -0
- package/dist/tools/subagent-manage.js +7 -7
- package/dist/tools/subagent-tool-names.d.ts +2 -2
- package/dist/tools/subagent-tool-names.js +2 -2
- package/dist/tools/task-manage/shared.js +4 -9
- package/dist/tools/task-manage/types.d.ts +4 -0
- package/dist/tui/app.js +22 -7
- package/dist/web/config.js +1 -1
- package/package.json +2 -1
- package/dist/shared/duration.d.ts +0 -2
- package/dist/shared/duration.js +0 -7
- package/dist/shared/file-stamp.d.ts +0 -10
- package/dist/shared/file-stamp.js +0 -19
- package/dist/shared/numeric.d.ts +0 -7
- package/dist/shared/numeric.js +0 -19
- package/dist/shared/shell-escape.d.ts +0 -5
- package/dist/shared/shell-escape.js +0 -7
- package/dist/shared/token-estimate.d.ts +0 -1
- package/dist/shared/token-estimate.js +0 -19
- /package/dist/{runtime → events}/event-commands.d.ts +0 -0
- /package/dist/{runtime → events}/event-commands.js +0 -0
- /package/dist/{runtime → events}/event-validation.d.ts +0 -0
- /package/dist/{runtime → events}/event-validation.js +0 -0
- /package/dist/{runtime → events}/events.js +0 -0
package/dist/memory/store.js
CHANGED
|
@@ -2,8 +2,8 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { appendFile, mkdir, readdir, readFile, rm, stat } from "node:fs/promises";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { writeFileAtomically } from "../shared/atomic-file.js";
|
|
5
|
-
import { readOptionalTextFile } from "../shared/fs-utils.js";
|
|
6
5
|
import { localDayKey } from "../shared/local-time.js";
|
|
6
|
+
import { readOptionalTextFile } from "../shared/os.js";
|
|
7
7
|
import { containsSecret } from "./secret-redaction.js";
|
|
8
8
|
import { hashMemoryContent } from "./tombstones.js";
|
|
9
9
|
const MEMORY_TYPES = ["user", "feedback", "project", "reference"];
|
package/dist/models/auth-cli.js
CHANGED
|
@@ -6,9 +6,9 @@
|
|
|
6
6
|
* login is a short, one-shot operation (spec 039 §5.1).
|
|
7
7
|
*/
|
|
8
8
|
import { createInterface } from "node:readline/promises";
|
|
9
|
+
import { prepareAppServices } from "../app-services.js";
|
|
9
10
|
import * as log from "../log.js";
|
|
10
11
|
import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, printBootstrapSummary, readCliVersion, } from "../runtime/app-home.js";
|
|
11
|
-
import { prepareAppServices } from "../runtime/bootstrap.js";
|
|
12
12
|
import { ReadlineLoginUi } from "./login-ui.js";
|
|
13
13
|
import { LoginCancelledError, listProviderLoginOptions, loginProvider, logoutProvider, renderAuthStatus, } from "./provider-login.js";
|
|
14
14
|
import { createModelRuntime, formatModelReference } from "./utils.js";
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
+
import { type JobRuntime } from "../agent/job-manager.js";
|
|
1
2
|
import type { AgentRunner } from "../agent/types.js";
|
|
2
3
|
import type { ChannelEvent } from "../channel/channel-event.js";
|
|
3
4
|
import { ChannelStore } from "../channel/store.js";
|
|
4
5
|
import { type Executor } from "../executor.js";
|
|
5
6
|
import { PipiclawSettingsManager } from "../settings.js";
|
|
7
|
+
import { type SubAgentRuntime } from "../subagents/runs.js";
|
|
6
8
|
import { type BootstrapIO, type BootstrapPaths } from "./app-home.js";
|
|
7
9
|
import { DingTalkBot, type DingTalkConfig, type DingTalkHandler } from "./dingtalk.js";
|
|
8
10
|
import { TaskDriver } from "./task-driver.js";
|
|
@@ -20,6 +22,8 @@ export interface AppContext {
|
|
|
20
22
|
shutdown: () => Promise<void>;
|
|
21
23
|
}
|
|
22
24
|
export interface RuntimeContext {
|
|
25
|
+
jobs: JobRuntime;
|
|
26
|
+
runs: SubAgentRuntime;
|
|
23
27
|
handler: DingTalkHandler;
|
|
24
28
|
store: ChannelStore;
|
|
25
29
|
/** Production driver instance, exposed so evals can invoke the real scan path. */
|
|
@@ -64,6 +68,7 @@ type TaskDriverLike = TaskDriver | {
|
|
|
64
68
|
nudge?(): void;
|
|
65
69
|
};
|
|
66
70
|
interface RuntimeContextOptions {
|
|
71
|
+
executor?: Executor;
|
|
67
72
|
paths: BootstrapPaths;
|
|
68
73
|
dingtalkConfig: DingTalkConfig;
|
|
69
74
|
createBot?: (handler: DingTalkHandler, config: DingTalkConfig) => DingTalkBot;
|
|
@@ -101,20 +106,5 @@ interface RuntimeContextOptions {
|
|
|
101
106
|
export declare function createRuntimeContext(options: RuntimeContextOptions): Promise<RuntimeContext & {
|
|
102
107
|
bot: DingTalkBot;
|
|
103
108
|
}>;
|
|
104
|
-
/**
|
|
105
|
-
* Transport-neutral app services shared by the DingTalk runtime and the terminal
|
|
106
|
-
* TUI: loads settings (surfacing load errors) and reports tool/security config
|
|
107
|
-
* diagnostics. Does NOT touch DingTalk config, so the TUI can call it without any
|
|
108
|
-
* DingTalk credentials.
|
|
109
|
-
*
|
|
110
|
-
* Extracted verbatim from `bootstrap()`; the DingTalk path calls it in the same
|
|
111
|
-
* position (after `loadConfig`, before `logStartup`) so its behavior is
|
|
112
|
-
* unchanged. Logging configuration is intentionally left to each caller
|
|
113
|
-
* (DingTalk: `createRuntimeContext`; TUI: right after this) to preserve the
|
|
114
|
-
* existing "diagnostics logged with default logging config" ordering.
|
|
115
|
-
*/
|
|
116
|
-
export declare function prepareAppServices(paths?: BootstrapPaths): {
|
|
117
|
-
settingsManager: PipiclawSettingsManager;
|
|
118
|
-
};
|
|
119
109
|
export declare function bootstrap(argv: string[], options?: BootstrapOptions): Promise<AppContext>;
|
|
120
110
|
export {};
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { mkdir, writeFile } from "fs/promises";
|
|
2
2
|
import { join, relative } from "path";
|
|
3
|
-
import {
|
|
3
|
+
import { createJobRuntime } from "../agent/job-manager.js";
|
|
4
4
|
import { loadDetachedMaintenanceContext } from "../agent/maintenance-context.js";
|
|
5
5
|
import { createRunner } from "../agent/runner-factory.js";
|
|
6
6
|
import { renderStatus } from "../agent/status-render.js";
|
|
7
7
|
import { scanWorkspaceForInterruptedTurns } from "../agent/turn-recovery.js";
|
|
8
|
+
import { prepareAppServices } from "../app-services.js";
|
|
8
9
|
import { createFreshActiveSession } from "../channel/active-session-store.js";
|
|
9
10
|
import { muteChannelContext } from "../channel/channel-context.js";
|
|
10
11
|
import { createChannelIndex } from "../channel/channel-index.js";
|
|
@@ -12,37 +13,36 @@ import { ensureChannelDir, getChannelDir } from "../channel/channel-paths.js";
|
|
|
12
13
|
import { resolveProjectScope } from "../channel/project-scope-store.js";
|
|
13
14
|
import { ChannelStore } from "../channel/store.js";
|
|
14
15
|
import { BUILT_IN_COMMANDS, formatUnknownCommandMessage, isRunnerBuiltInCommand, parseBuiltInCommand, slashCommandName, } from "../commands/catalog.js";
|
|
16
|
+
import { handleEventsCommand as runEventsCommand } from "../events/event-commands.js";
|
|
17
|
+
import { createEventsWatcher } from "../events/events.js";
|
|
15
18
|
import { createExecutor } from "../executor.js";
|
|
16
19
|
import * as log from "../log.js";
|
|
20
|
+
import { migrateMemoryMaintenanceStates } from "../memory/maintenance-migration.js";
|
|
17
21
|
import { MemoryMaintenanceScheduler } from "../memory/scheduler.js";
|
|
18
22
|
import { defaultModel } from "../models/utils.js";
|
|
19
23
|
import { loadSecurityConfigWithDiagnostics } from "../security/config.js";
|
|
20
24
|
import { flushSecurityLogs } from "../security/logger.js";
|
|
21
25
|
import { resolveProjectAccessPolicy } from "../security/project-scope.js";
|
|
22
26
|
import { PipiclawSettingsManager, TASK_DRIVER_SETTINGS } from "../settings.js";
|
|
23
|
-
import {
|
|
24
|
-
import { fileStamp } from "../shared/file-stamp.js";
|
|
27
|
+
import { fileStamp } from "../shared/format.js";
|
|
25
28
|
import { localStampForFilename } from "../shared/local-time.js";
|
|
26
29
|
import { errorMessage } from "../shared/text-utils.js";
|
|
27
30
|
import { sleepUnref } from "../shared/with-timeout.js";
|
|
28
31
|
import { loadDetachedSubAgentDiscovery } from "../subagents/detached-discovery.js";
|
|
29
|
-
import {
|
|
32
|
+
import { createSubAgentRuntime } from "../subagents/runs.js";
|
|
30
33
|
import { buildTaskStepBrief } from "../tasks/brief.js";
|
|
31
34
|
import { readActiveTasks } from "../tasks/ledger.js";
|
|
32
35
|
import { consumeTaskNotice } from "../tasks/steer.js";
|
|
33
36
|
import { readStoredTask } from "../tasks/store.js";
|
|
34
|
-
import { getToolsConfigPath, loadToolsConfig
|
|
37
|
+
import { getToolsConfigPath, loadToolsConfig } from "../tools/config.js";
|
|
35
38
|
import { getUsageLedger } from "../usage/ledger.js";
|
|
36
39
|
import { parseUsageMode, renderUsageReport } from "../usage/render.js";
|
|
37
40
|
import { BootstrapExitError, bootstrapAppHome, DEFAULT_BOOTSTRAP_PATHS, loadConfig, parseArgs, printBootstrapSummary, readCliVersion, } from "./app-home.js";
|
|
38
41
|
import { createDingTalkContext } from "./delivery.js";
|
|
39
42
|
import { DingTalkBot, } from "./dingtalk.js";
|
|
40
43
|
import { DurableDispatchService } from "./durable-dispatch.js";
|
|
41
|
-
import { handleEventsCommand as runEventsCommand } from "./event-commands.js";
|
|
42
|
-
import { createEventsWatcher } from "./events.js";
|
|
43
44
|
import { extensionForMimeType } from "./inbound-media.js";
|
|
44
45
|
import { handleProjectCommand as runProjectCommand } from "./project-commands.js";
|
|
45
|
-
import { installLlmProxy } from "./proxy.js";
|
|
46
46
|
import { handleSkillsCommand as runSkillsCommand } from "./skill-commands.js";
|
|
47
47
|
import { renderRunNotice, handleSubagentsCommand as runSubagentsCommand } from "./subagent-commands.js";
|
|
48
48
|
import { pauseTask, handleTasksCommand as runTasksCommand } from "./task-commands.js";
|
|
@@ -149,7 +149,7 @@ export async function forceEndStuckTurnAfterStop(input) {
|
|
|
149
149
|
return true;
|
|
150
150
|
}
|
|
151
151
|
function createDingTalkHandler(deps) {
|
|
152
|
-
const { options, store, channelRunners, sessionResetChains, activeTasks, stopWatchdogs, channelIndex, archiveIncomingMessage, getRunner, cliVersion, startedAt, isShuttingDown, getDurableDispatch,
|
|
152
|
+
const { options, store, channelRunners, sessionResetChains, activeTasks, stopWatchdogs, channelIndex, archiveIncomingMessage, getRunner, cliVersion, startedAt, isShuttingDown, getDurableDispatch, getJobs, getRuns, getTaskDriver, } = deps;
|
|
153
153
|
/**
|
|
154
154
|
* Turn a `[TASK_DRIVER:<id>]` dispatch into a task loop step: bind the runner to the task
|
|
155
155
|
* cycle's own session and replace the wake text with the step brief. Returns `undefined` for
|
|
@@ -369,6 +369,7 @@ function createDingTalkHandler(deps) {
|
|
|
369
369
|
case "subagents":
|
|
370
370
|
return runSubagentsCommand({
|
|
371
371
|
args,
|
|
372
|
+
runManager: getRuns().get(event.channelId),
|
|
372
373
|
channelId: event.channelId,
|
|
373
374
|
discovery: channelRunners.get(event.channelId)?.getSubAgentDiscoverySnapshot(),
|
|
374
375
|
// `roles` needs a role directory even for a channel that has never spoken this boot —
|
|
@@ -388,11 +389,12 @@ function createDingTalkHandler(deps) {
|
|
|
388
389
|
actor: "dingtalk-command",
|
|
389
390
|
isBusy: () => channelRunners.get(event.channelId)?.isBusy() ?? false,
|
|
390
391
|
listActiveBlockers: () => [
|
|
391
|
-
...
|
|
392
|
+
...getRuns()
|
|
393
|
+
.get(event.channelId)
|
|
392
394
|
.list()
|
|
393
395
|
.filter((record) => record.status === "running")
|
|
394
396
|
.map((record) => `subagent run \`${record.runId}\` (${record.agent})`),
|
|
395
|
-
...
|
|
397
|
+
...getJobs().runningLines(event.channelId),
|
|
396
398
|
],
|
|
397
399
|
// D4.2: dispose the cached runner so the next access rebuilds it under the new scope.
|
|
398
400
|
// The active-session ref is untouched — same session, new project root.
|
|
@@ -608,7 +610,7 @@ function createDingTalkHandler(deps) {
|
|
|
608
610
|
: jobTextMatch;
|
|
609
611
|
if (jobMatch) {
|
|
610
612
|
const [, jobId, jobTaskId] = jobMatch;
|
|
611
|
-
const claimed = await claimVerifiedJobWake(event, options.paths.workspaceDir,
|
|
613
|
+
const claimed = await claimVerifiedJobWake(event, options.paths.workspaceDir, getJobs().get(event.channelId), options.wakeTransitionHooks?.job);
|
|
612
614
|
if (claimed) {
|
|
613
615
|
await claimed.finish();
|
|
614
616
|
structuredWakeFinalized = true;
|
|
@@ -636,7 +638,7 @@ function createDingTalkHandler(deps) {
|
|
|
636
638
|
: delegationTextMatch;
|
|
637
639
|
if (delegationMatch) {
|
|
638
640
|
const [, runId, delegationTaskId] = delegationMatch;
|
|
639
|
-
const claimed = await claimVerifiedDelegationWake(event, options.paths.workspaceDir, options.wakeTransitionHooks?.subagent);
|
|
641
|
+
const claimed = await claimVerifiedDelegationWake(event, options.paths.workspaceDir, getRuns().get(event.channelId), options.wakeTransitionHooks?.subagent);
|
|
640
642
|
if (claimed) {
|
|
641
643
|
await claimed.finish();
|
|
642
644
|
structuredWakeFinalized = true;
|
|
@@ -697,6 +699,7 @@ function createDingTalkHandler(deps) {
|
|
|
697
699
|
return handler;
|
|
698
700
|
}
|
|
699
701
|
export async function createRuntimeContext(options) {
|
|
702
|
+
await migrateMemoryMaintenanceStates(options.paths.appHomeDir);
|
|
700
703
|
const startServices = options.startServices ?? true;
|
|
701
704
|
const registerSignalHandlers = options.registerSignalHandlers ?? true;
|
|
702
705
|
const store = new ChannelStore({ workingDir: options.paths.workspaceDir });
|
|
@@ -734,6 +737,8 @@ export async function createRuntimeContext(options) {
|
|
|
734
737
|
}
|
|
735
738
|
const channelDir = ensureChannelDir(options.paths.workspaceDir, channelId);
|
|
736
739
|
const runner = createRunner(channelId, channelDir, {
|
|
740
|
+
jobManager: jobs.get(channelId),
|
|
741
|
+
runManager: runs.get(channelId),
|
|
737
742
|
appHomeDir: options.paths.appHomeDir,
|
|
738
743
|
authConfigPath: options.paths.authConfigPath,
|
|
739
744
|
modelsConfigPath: options.paths.modelsConfigPath,
|
|
@@ -754,7 +759,8 @@ export async function createRuntimeContext(options) {
|
|
|
754
759
|
// task driver's own `notify` needs) — these two closures resolve them lazily, the same way
|
|
755
760
|
// `getRunner` above already resolves `bot` before its own declaration: nothing here calls
|
|
756
761
|
// through them until long after the whole function has finished setting up.
|
|
757
|
-
const
|
|
762
|
+
const getJobs = () => jobs;
|
|
763
|
+
const getRuns = () => runs;
|
|
758
764
|
const getTaskDriver = () => taskDriver;
|
|
759
765
|
const handler = createDingTalkHandler({
|
|
760
766
|
options,
|
|
@@ -770,7 +776,8 @@ export async function createRuntimeContext(options) {
|
|
|
770
776
|
startedAt,
|
|
771
777
|
isShuttingDown,
|
|
772
778
|
getDurableDispatch,
|
|
773
|
-
|
|
779
|
+
getJobs,
|
|
780
|
+
getRuns,
|
|
774
781
|
getTaskDriver,
|
|
775
782
|
});
|
|
776
783
|
const bot = options.createBot
|
|
@@ -790,10 +797,10 @@ export async function createRuntimeContext(options) {
|
|
|
790
797
|
`记录文件:state/dispatch/${record.id}.json(已保留,供排查)。`);
|
|
791
798
|
},
|
|
792
799
|
});
|
|
793
|
-
const executor = createExecutor();
|
|
800
|
+
const executor = options.executor ?? createExecutor();
|
|
794
801
|
// Background jobs get their persistence root and their way to wake a channel before any turn
|
|
795
802
|
// can start one, then re-adopt whatever survived the last shutdown (spec 031, D6).
|
|
796
|
-
|
|
803
|
+
const jobs = createJobRuntime(executor, {
|
|
797
804
|
jobsStateDir: join(options.paths.appHomeDir, "state", "jobs"),
|
|
798
805
|
workspaceDir: options.paths.workspaceDir,
|
|
799
806
|
dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
|
|
@@ -801,7 +808,7 @@ export async function createRuntimeContext(options) {
|
|
|
801
808
|
});
|
|
802
809
|
// Delegation runs get the same treatment (spec 040, D1/D7): persistence root, wake delivery,
|
|
803
810
|
// and the usage/archive authority, wired before any turn can start a run.
|
|
804
|
-
|
|
811
|
+
const runs = createSubAgentRuntime({
|
|
805
812
|
stateDir: join(options.paths.appHomeDir, "state", "subagent-runs"),
|
|
806
813
|
dispatch: (event) => durableDispatch?.dispatch(event) ?? false,
|
|
807
814
|
// P0-1/P1a: a best-effort out-of-band notice, independent of the completion wake — it reaches
|
|
@@ -826,8 +833,9 @@ export async function createRuntimeContext(options) {
|
|
|
826
833
|
// Spec 042 D11: `restoreChannelJobs` used to be a bare `void` while `restoreAllSubAgentRuns`
|
|
827
834
|
// was already awaited — the same admission race P0-1 closed for delegation runs was still open
|
|
828
835
|
// for background jobs.
|
|
829
|
-
await
|
|
830
|
-
await
|
|
836
|
+
await jobs.restore();
|
|
837
|
+
await runs.restore();
|
|
838
|
+
runs.start();
|
|
831
839
|
// Spec 043, D10 point 1: repair any turn interrupted by the last shutdown/crash before opening
|
|
832
840
|
// admission — a message routed to a still-dangling session would 400 against the provider on
|
|
833
841
|
// every attempt (F3) until a human ran /new. Runs before bot.start() for the same reason as
|
|
@@ -917,7 +925,8 @@ export async function createRuntimeContext(options) {
|
|
|
917
925
|
durableDispatch?.stop();
|
|
918
926
|
memoryMaintenanceScheduler.stop();
|
|
919
927
|
eventsWatcher.stop();
|
|
920
|
-
|
|
928
|
+
runs.stop();
|
|
929
|
+
jobs.stop();
|
|
921
930
|
await bot.stop();
|
|
922
931
|
const runningTasks = Array.from(activeTasks);
|
|
923
932
|
if (runningTasks.length > 0) {
|
|
@@ -1004,6 +1013,8 @@ export async function createRuntimeContext(options) {
|
|
|
1004
1013
|
}
|
|
1005
1014
|
return {
|
|
1006
1015
|
handler,
|
|
1016
|
+
jobs,
|
|
1017
|
+
runs,
|
|
1007
1018
|
store,
|
|
1008
1019
|
bot,
|
|
1009
1020
|
taskDriver,
|
|
@@ -1011,41 +1022,6 @@ export async function createRuntimeContext(options) {
|
|
|
1011
1022
|
shutdown: shutdownWithReason,
|
|
1012
1023
|
};
|
|
1013
1024
|
}
|
|
1014
|
-
/**
|
|
1015
|
-
* Transport-neutral app services shared by the DingTalk runtime and the terminal
|
|
1016
|
-
* TUI: loads settings (surfacing load errors) and reports tool/security config
|
|
1017
|
-
* diagnostics. Does NOT touch DingTalk config, so the TUI can call it without any
|
|
1018
|
-
* DingTalk credentials.
|
|
1019
|
-
*
|
|
1020
|
-
* Extracted verbatim from `bootstrap()`; the DingTalk path calls it in the same
|
|
1021
|
-
* position (after `loadConfig`, before `logStartup`) so its behavior is
|
|
1022
|
-
* unchanged. Logging configuration is intentionally left to each caller
|
|
1023
|
-
* (DingTalk: `createRuntimeContext`; TUI: right after this) to preserve the
|
|
1024
|
-
* existing "diagnostics logged with default logging config" ordering.
|
|
1025
|
-
*/
|
|
1026
|
-
export function prepareAppServices(paths = DEFAULT_BOOTSTRAP_PATHS) {
|
|
1027
|
-
// Shared by the DingTalk daemon and the TUI (both call prepareAppServices), so this
|
|
1028
|
-
// covers every entrypoint that talks to an LLM provider.
|
|
1029
|
-
installLlmProxy();
|
|
1030
|
-
const settingsManager = new PipiclawSettingsManager(paths.appHomeDir);
|
|
1031
|
-
for (const { scope, error } of settingsManager.drainErrors()) {
|
|
1032
|
-
log.logWarning(`Failed to load ${scope} settings`, `${error.message}\n${paths.settingsConfigPath}`);
|
|
1033
|
-
}
|
|
1034
|
-
// Errors already went out above with a richer message; this pass exists for the
|
|
1035
|
-
// warnings, chiefly retired settings keys (spec 035 D3).
|
|
1036
|
-
for (const diagnostic of settingsManager.getDiagnostics()) {
|
|
1037
|
-
if (diagnostic.severity === "error")
|
|
1038
|
-
continue;
|
|
1039
|
-
log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
|
|
1040
|
-
}
|
|
1041
|
-
for (const diagnostic of loadToolsConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
|
|
1042
|
-
log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
|
|
1043
|
-
}
|
|
1044
|
-
for (const diagnostic of loadSecurityConfigWithDiagnostics(paths.appHomeDir).diagnostics) {
|
|
1045
|
-
log.logWarning(formatConfigDiagnostic(diagnostic), diagnostic.path);
|
|
1046
|
-
}
|
|
1047
|
-
return { settingsManager };
|
|
1048
|
-
}
|
|
1049
1025
|
export async function bootstrap(argv, options = {}) {
|
|
1050
1026
|
const io = options.io ?? console;
|
|
1051
1027
|
const paths = options.paths ?? DEFAULT_BOOTSTRAP_PATHS;
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import type { SubAgentDiscoveryResult } from "../subagents/discovery.js";
|
|
2
|
-
import {
|
|
2
|
+
import type { RunNotice, SubAgentRunManager } from "../subagents/runs.js";
|
|
3
3
|
/**
|
|
4
4
|
* `/subagents` — the human control path that does not depend on the model (spec 040 D6, polished
|
|
5
5
|
* by spec 041). Mirrors `task-commands.ts`'s shape: pure functions returning markdown, no
|
|
6
6
|
* bot/event coupling.
|
|
7
7
|
*/
|
|
8
8
|
export interface HandleSubagentsCommandOptions {
|
|
9
|
+
runManager: SubAgentRunManager;
|
|
9
10
|
args: string;
|
|
10
11
|
channelId: string;
|
|
11
12
|
/** Best-effort role-directory snapshot for `roles` / the overview tail; omitted when no runner
|
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import { readFile } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { renderSubcommandUsage } from "../commands/catalog.js";
|
|
4
|
-
import { formatDuration } from "../shared/
|
|
4
|
+
import { formatDuration } from "../shared/format.js";
|
|
5
5
|
import { errorMessage } from "../shared/text-utils.js";
|
|
6
6
|
import { formatCost, formatRunDuration, harnessLabel } from "../subagents/format.js";
|
|
7
|
-
import { getSubAgentRunManager } from "../subagents/runs.js";
|
|
8
7
|
function usage() {
|
|
9
8
|
return `${renderSubcommandUsage("subagents")}\n\n\`runId\` 支持不带 \`run_\` 前缀的简写,只要能唯一匹配即可,例如 \`show a1b2c3\`。`;
|
|
10
9
|
}
|
|
@@ -113,7 +112,7 @@ function capListForDisplay(records) {
|
|
|
113
112
|
};
|
|
114
113
|
}
|
|
115
114
|
async function listRuns(options, filter) {
|
|
116
|
-
const records =
|
|
115
|
+
const records = options.runManager.list();
|
|
117
116
|
if (records.length === 0)
|
|
118
117
|
return "**委派 Run**\n\n没有委派记录。";
|
|
119
118
|
const running = records.filter((record) => record.status === "running").sort((a, b) => b.startedAt - a.startedAt);
|
|
@@ -170,8 +169,8 @@ function formatRunResolution(resolution, ref) {
|
|
|
170
169
|
}
|
|
171
170
|
return undefined;
|
|
172
171
|
}
|
|
173
|
-
async function showRun(
|
|
174
|
-
const resolution =
|
|
172
|
+
async function showRun(manager, ref) {
|
|
173
|
+
const resolution = manager.resolveRef(ref);
|
|
175
174
|
const error = formatRunResolution(resolution, ref);
|
|
176
175
|
if (error || resolution.kind !== "found")
|
|
177
176
|
return error ?? `未找到 run:\`${ref}\``;
|
|
@@ -225,8 +224,8 @@ async function showRun(channelId, ref) {
|
|
|
225
224
|
}
|
|
226
225
|
return lines.join("\n");
|
|
227
226
|
}
|
|
228
|
-
async function showOutput(
|
|
229
|
-
const resolution =
|
|
227
|
+
async function showOutput(manager, ref) {
|
|
228
|
+
const resolution = manager.resolveRef(ref);
|
|
230
229
|
const error = formatRunResolution(resolution, ref);
|
|
231
230
|
if (error || resolution.kind !== "found")
|
|
232
231
|
return error ?? `未找到 run:\`${ref}\``;
|
|
@@ -240,8 +239,7 @@ async function showOutput(channelId, ref) {
|
|
|
240
239
|
const truncatedNote = outputText.length > tail.length ? `(只显示末尾 ${OUTPUT_TAIL_CHARS} 字符,完整内容见上方产物目录)\n\n` : "";
|
|
241
240
|
return `**Run \`${record.runId}\` 的产出**\n\n${truncatedNote}\`\`\`\n${tail}\n\`\`\``;
|
|
242
241
|
}
|
|
243
|
-
async function cancelRun(
|
|
244
|
-
const manager = getSubAgentRunManager(channelId);
|
|
242
|
+
async function cancelRun(manager, ref) {
|
|
245
243
|
if (ref === "all") {
|
|
246
244
|
const running = manager.list().filter((record) => record.status === "running");
|
|
247
245
|
if (running.length === 0)
|
|
@@ -352,11 +350,11 @@ export async function handleSubagentsCommand(options) {
|
|
|
352
350
|
case "list":
|
|
353
351
|
return await listRuns(options, command.filter);
|
|
354
352
|
case "show":
|
|
355
|
-
return await showRun(options.
|
|
353
|
+
return await showRun(options.runManager, command.ref);
|
|
356
354
|
case "output":
|
|
357
|
-
return await showOutput(options.
|
|
355
|
+
return await showOutput(options.runManager, command.ref);
|
|
358
356
|
case "cancel":
|
|
359
|
-
return await cancelRun(options.
|
|
357
|
+
return await cancelRun(options.runManager, command.ref);
|
|
360
358
|
case "roles":
|
|
361
359
|
return await showRoles(options, command.name);
|
|
362
360
|
}
|
|
@@ -4,10 +4,9 @@
|
|
|
4
4
|
* over an explicit `event`/`workspaceDir`/`executor`, with no dependency on
|
|
5
5
|
* `createRuntimeContext`'s closures.
|
|
6
6
|
*/
|
|
7
|
-
import {
|
|
7
|
+
import type { ChannelJobManager, JobSnapshot } from "../agent/job-manager.js";
|
|
8
8
|
import type { ChannelEvent } from "../channel/channel-event.js";
|
|
9
|
-
import type {
|
|
10
|
-
import { type RunRecord } from "../subagents/runs.js";
|
|
9
|
+
import type { RunRecord, SubAgentRunManager } from "../subagents/runs.js";
|
|
11
10
|
/**
|
|
12
11
|
* Whether a `[JOB:<jobId>] ... belongs to task <taskId>.` wake actually names a job that: exists
|
|
13
12
|
* on this channel, has actually finished (a still-`running` job cannot have produced this wake —
|
|
@@ -46,7 +45,7 @@ export interface WakeTaskTransitionHooks {
|
|
|
46
45
|
/** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
|
|
47
46
|
* final marker separate lets transports such as TUI mark it consumed only after they have accepted
|
|
48
47
|
* the corresponding turn; a rejected submit remains replayable in the same or next process. */
|
|
49
|
-
export declare function claimVerifiedDelegationWake(event: ChannelEvent, workspaceDir: string, hooks?: WakeTaskTransitionHooks): Promise<ClaimedDelegationWake | undefined>;
|
|
48
|
+
export declare function claimVerifiedDelegationWake(event: ChannelEvent, workspaceDir: string, runManager: SubAgentRunManager, hooks?: WakeTaskTransitionHooks): Promise<ClaimedDelegationWake | undefined>;
|
|
50
49
|
export interface ClaimedJobWake {
|
|
51
50
|
taskId: string;
|
|
52
51
|
activated: boolean;
|
|
@@ -57,4 +56,4 @@ export interface ClaimedJobWake {
|
|
|
57
56
|
/** Same shape as `claimVerifiedDelegationWake`, for a `[JOB:<jobId>] ... belongs to task
|
|
58
57
|
* <taskId>.` completion wake. A background job has no rollback bookkeeping — its wake
|
|
59
58
|
* activation is a single unconditional step — so `ClaimedJobWake` omits `rollback`. */
|
|
60
|
-
export declare function claimVerifiedJobWake(event: ChannelEvent, workspaceDir: string,
|
|
59
|
+
export declare function claimVerifiedJobWake(event: ChannelEvent, workspaceDir: string, jobManager: ChannelJobManager, hooks?: WakeTaskTransitionHooks): Promise<ClaimedJobWake | undefined>;
|
|
@@ -1,12 +1,4 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Verifying and claiming a background job's or delegation run's completion wake before it may
|
|
3
|
-
* activate a parked task (spec 040, D7/T9). Split out of `bootstrap.ts`: these are pure functions
|
|
4
|
-
* over an explicit `event`/`workspaceDir`/`executor`, with no dependency on
|
|
5
|
-
* `createRuntimeContext`'s closures.
|
|
6
|
-
*/
|
|
7
|
-
import { getChannelJobManager } from "../agent/job-manager.js";
|
|
8
1
|
import { getChannelDir } from "../channel/channel-paths.js";
|
|
9
|
-
import { getSubAgentRunManager } from "../subagents/runs.js";
|
|
10
2
|
import { parkTask, readStoredTask, redeemTicket } from "../tasks/store.js";
|
|
11
3
|
/**
|
|
12
4
|
* True when `taskId` is already `open` and not paused — i.e. the driver already owns advancing
|
|
@@ -55,11 +47,10 @@ export function isTrustedInternalWake(event, kind, resourceId, taskId) {
|
|
|
55
47
|
/** Claim and activate a producer-created delegation wake without consuming it yet. Keeping the
|
|
56
48
|
* final marker separate lets transports such as TUI mark it consumed only after they have accepted
|
|
57
49
|
* the corresponding turn; a rejected submit remains replayable in the same or next process. */
|
|
58
|
-
export async function claimVerifiedDelegationWake(event, workspaceDir, hooks) {
|
|
50
|
+
export async function claimVerifiedDelegationWake(event, workspaceDir, runManager, hooks) {
|
|
59
51
|
const wake = event.internalWake;
|
|
60
52
|
if (wake?.kind !== "subagent")
|
|
61
53
|
return undefined;
|
|
62
|
-
const runManager = getSubAgentRunManager(event.channelId);
|
|
63
54
|
const record = runManager.get(wake.resourceId);
|
|
64
55
|
if (!isTrustedInternalWake(event, "subagent", wake.resourceId, wake.taskId) ||
|
|
65
56
|
!isVerifiedDelegationWake(record, wake.taskId) ||
|
|
@@ -91,11 +82,10 @@ export async function claimVerifiedDelegationWake(event, workspaceDir, hooks) {
|
|
|
91
82
|
/** Same shape as `claimVerifiedDelegationWake`, for a `[JOB:<jobId>] ... belongs to task
|
|
92
83
|
* <taskId>.` completion wake. A background job has no rollback bookkeeping — its wake
|
|
93
84
|
* activation is a single unconditional step — so `ClaimedJobWake` omits `rollback`. */
|
|
94
|
-
export async function claimVerifiedJobWake(event, workspaceDir,
|
|
85
|
+
export async function claimVerifiedJobWake(event, workspaceDir, jobManager, hooks) {
|
|
95
86
|
const wake = event.internalWake;
|
|
96
87
|
if (wake?.kind !== "job")
|
|
97
88
|
return undefined;
|
|
98
|
-
const jobManager = getChannelJobManager(event.channelId, executor);
|
|
99
89
|
const jobs = await jobManager.list();
|
|
100
90
|
if (!isTrustedInternalWake(event, "job", wake.resourceId, wake.taskId) ||
|
|
101
91
|
!isVerifiedJobWake(jobs, wake.resourceId, wake.taskId) ||
|
package/dist/security/types.d.ts
CHANGED
|
@@ -36,6 +36,13 @@ export interface SecurityConfig {
|
|
|
36
36
|
allowedRoots?: string[];
|
|
37
37
|
};
|
|
38
38
|
}
|
|
39
|
+
/**
|
|
40
|
+
* Every top-level `security.json` key, read by `test/config-reference-coverage.test.ts` to check
|
|
41
|
+
* that `docs/security.md` still mentions each one. Kept in sync with `SecurityConfig` by
|
|
42
|
+
* `satisfies` (rejects an extra/misspelled entry) and `AssertNoMissingKeys` (rejects a field with
|
|
43
|
+
* no entry here) — both at `npm run typecheck`.
|
|
44
|
+
*/
|
|
45
|
+
export declare const SECURITY_CONFIG_TOP_LEVEL_KEYS: readonly ["enabled", "commandGuard", "pathGuard", "networkGuard", "audit", "projectAccess"];
|
|
39
46
|
export interface SecurityRuntimeContext {
|
|
40
47
|
agentWorkspaceDir: string;
|
|
41
48
|
projectRoot?: string;
|
package/dist/security/types.js
CHANGED
|
@@ -1 +1,16 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Every top-level `security.json` key, read by `test/config-reference-coverage.test.ts` to check
|
|
3
|
+
* that `docs/security.md` still mentions each one. Kept in sync with `SecurityConfig` by
|
|
4
|
+
* `satisfies` (rejects an extra/misspelled entry) and `AssertNoMissingKeys` (rejects a field with
|
|
5
|
+
* no entry here) — both at `npm run typecheck`.
|
|
6
|
+
*/
|
|
7
|
+
export const SECURITY_CONFIG_TOP_LEVEL_KEYS = [
|
|
8
|
+
"enabled",
|
|
9
|
+
"commandGuard",
|
|
10
|
+
"pathGuard",
|
|
11
|
+
"networkGuard",
|
|
12
|
+
"audit",
|
|
13
|
+
"projectAccess",
|
|
14
|
+
];
|
|
15
|
+
const _securityConfigKeysComplete = true;
|
|
16
|
+
void _securityConfigKeysComplete;
|
package/dist/settings.d.ts
CHANGED
|
@@ -105,6 +105,14 @@ export interface PipiclawSettings {
|
|
|
105
105
|
tui?: Partial<PipiclawTuiSettings>;
|
|
106
106
|
delegation?: Partial<PipiclawDelegationSettings>;
|
|
107
107
|
}
|
|
108
|
+
/**
|
|
109
|
+
* Every top-level `settings.json` key, read by `test/config-reference-coverage.test.ts` to check
|
|
110
|
+
* that `docs/configuration-reference.md` still mentions each one. The two lines below keep this
|
|
111
|
+
* list from drifting out of sync with `PipiclawSettings` itself: `satisfies` rejects an extra or
|
|
112
|
+
* misspelled entry, and the `AssertNoMissingKeys` check rejects an interface field with no entry
|
|
113
|
+
* here — both at `npm run typecheck`, not by trusting a human to update two places together.
|
|
114
|
+
*/
|
|
115
|
+
export declare const SETTINGS_TOP_LEVEL_KEYS: readonly ["defaultProvider", "defaultModel", "defaultThinkingLevel", "fallbackModel", "subagentModel", "compaction", "retry", "memoryMaintenance", "sessionSearch", "logging", "tui", "delegation"];
|
|
108
116
|
export interface PipiclawTuiSettings {
|
|
109
117
|
/**
|
|
110
118
|
* Output shape for the terminal TUI, reusing the DingTalk response-mode
|
package/dist/settings.js
CHANGED
|
@@ -11,7 +11,30 @@ import { dirname, join } from "path";
|
|
|
11
11
|
import * as log from "./log.js";
|
|
12
12
|
import { getMemoryMaintenanceTuning } from "./memory/maintenance-tuning.js";
|
|
13
13
|
import { writeFileAtomicallySync } from "./shared/atomic-file.js";
|
|
14
|
-
import { fileStamp } from "./shared/
|
|
14
|
+
import { fileStamp } from "./shared/format.js";
|
|
15
|
+
/**
|
|
16
|
+
* Every top-level `settings.json` key, read by `test/config-reference-coverage.test.ts` to check
|
|
17
|
+
* that `docs/configuration-reference.md` still mentions each one. The two lines below keep this
|
|
18
|
+
* list from drifting out of sync with `PipiclawSettings` itself: `satisfies` rejects an extra or
|
|
19
|
+
* misspelled entry, and the `AssertNoMissingKeys` check rejects an interface field with no entry
|
|
20
|
+
* here — both at `npm run typecheck`, not by trusting a human to update two places together.
|
|
21
|
+
*/
|
|
22
|
+
export const SETTINGS_TOP_LEVEL_KEYS = [
|
|
23
|
+
"defaultProvider",
|
|
24
|
+
"defaultModel",
|
|
25
|
+
"defaultThinkingLevel",
|
|
26
|
+
"fallbackModel",
|
|
27
|
+
"subagentModel",
|
|
28
|
+
"compaction",
|
|
29
|
+
"retry",
|
|
30
|
+
"memoryMaintenance",
|
|
31
|
+
"sessionSearch",
|
|
32
|
+
"logging",
|
|
33
|
+
"tui",
|
|
34
|
+
"delegation",
|
|
35
|
+
];
|
|
36
|
+
const _settingsKeysComplete = true;
|
|
37
|
+
void _settingsKeysComplete;
|
|
15
38
|
const DEFAULT_TUI = {
|
|
16
39
|
responseMode: "full_progress_then_plain_final",
|
|
17
40
|
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compile-time completeness check for a runtime key list paired with a config interface. Assign
|
|
3
|
+
* the result to a `const` typed `true` (then `void` it to satisfy `noUnusedLocals`): if `K` is
|
|
4
|
+
* missing any key of `T`, the check's type becomes `never` and the assignment fails to
|
|
5
|
+
* typecheck. This is what keeps a documentation-coverage test's key list (e.g.
|
|
6
|
+
* `SETTINGS_TOP_LEVEL_KEYS` in `settings.ts`) from silently drifting out of sync with the
|
|
7
|
+
* interface it documents when a field is added — `npm run typecheck` catches it, not a human
|
|
8
|
+
* remembering to update two places.
|
|
9
|
+
*
|
|
10
|
+
* Only checks for *missing* keys. Pair the key list's own type with
|
|
11
|
+
* `satisfies readonly (keyof T)[]` to also reject an extra or misspelled key.
|
|
12
|
+
*/
|
|
13
|
+
export type AssertNoMissingKeys<T, K extends readonly (keyof T)[]> = Exclude<keyof T, K[number]> extends never ? true : never;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Render a millisecond duration as compact human text (`"42s"`, `"3m7s"`). */
|
|
2
|
+
export declare function formatDuration(ms: number): string;
|
|
3
|
+
/**
|
|
4
|
+
* Coerce an untrusted numeric config/request value into an integer within `[minimum, maximum]`,
|
|
5
|
+
* falling back to `fallback` for anything not a finite number or out of range. Shared by the
|
|
6
|
+
* app-level config loaders (`tools.json`) and web request parameter resolution — both need the
|
|
7
|
+
* same "trust nothing, fail closed to a safe default" numeric parsing.
|
|
8
|
+
*/
|
|
9
|
+
export declare function clampInteger(value: unknown, fallback: number, minimum: number, maximum?: number): number;
|
|
10
|
+
export declare function estimateTokens(text: string): number;
|
|
11
|
+
/**
|
|
12
|
+
* A cheap change token for a config file: `mtime:ctime:size`, or `""` when the file
|
|
13
|
+
* cannot be stat'ed (missing or unreadable — itself a stable state worth caching).
|
|
14
|
+
*
|
|
15
|
+
* Used by the hot re-read paths (`settings.json` on every driver/maintenance tick,
|
|
16
|
+
* `tools.json` on every driver tick) to skip a JSON parse when nothing changed. Same
|
|
17
|
+
* triple as the task-ledger parse cache: mtime alone misses an atomic-rename overwrite
|
|
18
|
+
* that preserves the timestamp, ctime catches the rename, size catches the rest.
|
|
19
|
+
*/
|
|
20
|
+
export declare function fileStamp(path: string): string;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { statSync } from "node:fs";
|
|
2
|
+
/** Render a millisecond duration as compact human text (`"42s"`, `"3m7s"`). */
|
|
3
|
+
export function formatDuration(ms) {
|
|
4
|
+
const seconds = Math.round(ms / 1000);
|
|
5
|
+
if (seconds < 60)
|
|
6
|
+
return `${seconds}s`;
|
|
7
|
+
return `${Math.floor(seconds / 60)}m${seconds % 60}s`;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Coerce an untrusted numeric config/request value into an integer within `[minimum, maximum]`,
|
|
11
|
+
* falling back to `fallback` for anything not a finite number or out of range. Shared by the
|
|
12
|
+
* app-level config loaders (`tools.json`) and web request parameter resolution — both need the
|
|
13
|
+
* same "trust nothing, fail closed to a safe default" numeric parsing.
|
|
14
|
+
*/
|
|
15
|
+
export function clampInteger(value, fallback, minimum, maximum) {
|
|
16
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
17
|
+
return fallback;
|
|
18
|
+
}
|
|
19
|
+
const normalized = Math.floor(value);
|
|
20
|
+
if (normalized < minimum) {
|
|
21
|
+
return fallback;
|
|
22
|
+
}
|
|
23
|
+
if (maximum !== undefined && normalized > maximum) {
|
|
24
|
+
return fallback;
|
|
25
|
+
}
|
|
26
|
+
return normalized;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Rough token estimate, shared by everything that has to reason about context size without
|
|
30
|
+
* calling a tokenizer. CJK runs about one token per character, Latin text about four characters
|
|
31
|
+
* per token; the provider's real tokenizer is the authority, and the usage ledger records what
|
|
32
|
+
* it billed.
|
|
33
|
+
*
|
|
34
|
+
* The script split matters wherever the estimate gates behavior rather than just reporting: a
|
|
35
|
+
* flat characters-per-token ratio tuned for Latin text underestimates Chinese input roughly
|
|
36
|
+
* threefold, so a budget check would clear a message that in fact does not fit.
|
|
37
|
+
*/
|
|
38
|
+
const CJK_REGEX = /\p{Script=Han}|\p{Script=Hiragana}|\p{Script=Katakana}|\p{Script=Hangul}/u;
|
|
39
|
+
export function estimateTokens(text) {
|
|
40
|
+
let cjk = 0;
|
|
41
|
+
for (const char of text) {
|
|
42
|
+
if (CJK_REGEX.test(char))
|
|
43
|
+
cjk++;
|
|
44
|
+
}
|
|
45
|
+
return Math.ceil(cjk + (text.length - cjk) / 4);
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A cheap change token for a config file: `mtime:ctime:size`, or `""` when the file
|
|
49
|
+
* cannot be stat'ed (missing or unreadable — itself a stable state worth caching).
|
|
50
|
+
*
|
|
51
|
+
* Used by the hot re-read paths (`settings.json` on every driver/maintenance tick,
|
|
52
|
+
* `tools.json` on every driver tick) to skip a JSON parse when nothing changed. Same
|
|
53
|
+
* triple as the task-ledger parse cache: mtime alone misses an atomic-rename overwrite
|
|
54
|
+
* that preserves the timestamp, ctime catches the rename, size catches the rest.
|
|
55
|
+
*/
|
|
56
|
+
export function fileStamp(path) {
|
|
57
|
+
try {
|
|
58
|
+
const stats = statSync(path);
|
|
59
|
+
return `${stats.mtimeMs}:${stats.ctimeMs}:${stats.size}`;
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
return "";
|
|
63
|
+
}
|
|
64
|
+
}
|