zam-core 0.3.12 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -158,6 +158,17 @@ interface ConnectionOptions {
158
158
  /** Explicit provider; overrides ZAM_DB_PROVIDER and the credentials mode. */
159
159
  provider?: DatabaseProvider;
160
160
  }
161
+ interface DatabaseTargetInfo {
162
+ /** User-facing category of database target selected for this connection. */
163
+ kind: "local" | "turso-native" | "turso-remote" | "turso-replica";
164
+ /** Driver/provider that will be used for the selected target. */
165
+ provider: DatabaseProvider;
166
+ /** Local filesystem path or remote URL selected as the database target. */
167
+ location: string;
168
+ /** Turso primary URL when the selected target is an embedded replica. */
169
+ syncUrl?: string;
170
+ }
171
+ declare function getDatabaseTargetInfo(options?: ConnectionOptions): DatabaseTargetInfo;
161
172
  /**
162
173
  * Open (or create) the ZAM database.
163
174
  * Uses configured Turso credentials for the default database when present.
@@ -509,8 +520,10 @@ declare function deleteCardForUser(db: Database, tokenId: string, userId: string
509
520
  * then by due_at ascending (oldest first).
510
521
  *
511
522
  * Ported from the PoC's due-tokens command.
523
+ *
524
+ * When `domain` is set, only due cards in that token domain are returned.
512
525
  */
513
- declare function getDueCards(db: Database, userId: string, now?: string): Promise<DueCard[]>;
526
+ declare function getDueCards(db: Database, userId: string, now?: string, domain?: string): Promise<DueCard[]>;
514
527
  /**
515
528
  * Get all blocked cards for a user.
516
529
  *
@@ -967,6 +980,139 @@ declare function getMonitorLogStats(sessionId: string): {
967
980
  lineCount: number;
968
981
  };
969
982
 
983
+ /**
984
+ * Observer permission policy — Layer 2 of the two-layer consent model
985
+ * (see docs/adr/0001-observer-permission-model.md).
986
+ *
987
+ * A host (the CLI permission system today, MCP tool-consent later) decides
988
+ * WHETHER an agent may invoke the observer. This module decides WHAT a given
989
+ * capture is then allowed to see — enforced by ZAM, because ZAM holds the
990
+ * camera. The policy is user-configurable through `zam settings` (the
991
+ * `observer.*` keys in `user_config`) and resolved here into a typed value with
992
+ * safe defaults.
993
+ *
994
+ * The decision functions are pure so they can be unit-tested without a DB or a
995
+ * live screen, and reused unchanged under a future `zam mcp serve`.
996
+ */
997
+
998
+ declare const OBSERVER_POLICY_VERSION: 1;
999
+ type ObserverScope = "off" | "window" | "fullscreen";
1000
+ type ObserverConsent = "per-capture" | "per-session" | "standing";
1001
+ type ObserverRetention = "none" | "session" | "persist";
1002
+ interface ObserverPolicy {
1003
+ version: typeof OBSERVER_POLICY_VERSION;
1004
+ /** "off" disables capture; "window" requires a target; "fullscreen" permits an untargeted grab. */
1005
+ scope: ObserverScope;
1006
+ /** Lower-cased process names permitted under window scope (empty = any non-denied window). */
1007
+ allowlist: string[];
1008
+ /** Lower-cased process/title fragments the user never wants captured (added to the built-in set). */
1009
+ denylist: string[];
1010
+ consent: ObserverConsent;
1011
+ retention: ObserverRetention;
1012
+ redactWindowTitles: boolean;
1013
+ audioOptIn: boolean;
1014
+ }
1015
+ declare const DEFAULT_OBSERVER_POLICY: ObserverPolicy;
1016
+ /**
1017
+ * Built-in sensitive process/title fragments that are ALWAYS non-observable.
1018
+ * User config may extend the effective denylist but can never re-enable capture
1019
+ * of these — a user `allowlist` cannot override the built-in floor. Matching is
1020
+ * case-insensitive substring against process name and window title. This mirrors
1021
+ * a conservative subset of the native Rust observer's sensitive-context set.
1022
+ */
1023
+ declare const BUILT_IN_SENSITIVE_MATCHERS: readonly string[];
1024
+ type ObserverSettingKey = "observer.scope" | "observer.allowlist" | "observer.denylist" | "observer.consent" | "observer.retention" | "observer.redact_titles" | "observer.audio";
1025
+ /**
1026
+ * Public wrapper around the allow/denylist normalizer so CLI list mutation
1027
+ * (`zam observer grant/revoke`) parses entries exactly like resolveObserverPolicy.
1028
+ */
1029
+ declare function parseObserverList(raw: string | undefined): string[];
1030
+ /** Pure: build a policy from raw setting strings (no DB access). */
1031
+ declare function parseObserverPolicy(raw: Partial<Record<ObserverSettingKey, string>>, defaults?: {
1032
+ scope: ObserverScope;
1033
+ consent: ObserverConsent;
1034
+ }): ObserverPolicy;
1035
+ /** Read the policy from `user_config`, falling back to active symbiosis mode presets, then safe defaults. */
1036
+ declare function resolveObserverPolicy(db: Database): Promise<ObserverPolicy>;
1037
+ type CaptureDenialReason = "scope-off" | "scope-requires-target" | "denylisted" | "not-allowlisted" | "sensitive";
1038
+ type CaptureDecision = {
1039
+ allowed: true;
1040
+ } | {
1041
+ allowed: false;
1042
+ reason: string;
1043
+ denialReason: CaptureDenialReason;
1044
+ };
1045
+ interface CaptureRequest {
1046
+ /** Whether the caller specified a concrete window target (--hwnd or --process-name). */
1047
+ hasExplicitTarget: boolean;
1048
+ /** The requested process name, if any (comparison is case-insensitive). */
1049
+ requestedProcessName: string | null;
1050
+ }
1051
+ interface ResolvedCaptureTarget {
1052
+ /** printwindow | copyfromscreen | fullscreen | provided | screencapture-* */
1053
+ method: string;
1054
+ processName: string | null;
1055
+ windowTitle: string | null;
1056
+ }
1057
+ /** Built-in sensitive match (authoritative — user config cannot override). */
1058
+ declare function matchBuiltInSensitive(processName: string | null, windowTitle: string | null): string | null;
1059
+ /** User-denylist match. */
1060
+ declare function matchDenylist(policy: ObserverPolicy, processName: string | null, windowTitle: string | null): string | null;
1061
+ /**
1062
+ * Phase 1 — decide before any pixels are grabbed, from scope plus the requested
1063
+ * target. Cheap denials (disabled observer, missing target, an explicitly named
1064
+ * sensitive/denied process) happen here so no screenshot is taken at all.
1065
+ */
1066
+ declare function decidePreCapture(policy: ObserverPolicy, request: CaptureRequest): CaptureDecision;
1067
+ /**
1068
+ * Phase 2 — decide after the window was resolved into a concrete target. This
1069
+ * is the first point where the real process/title are known, so the
1070
+ * sensitive/denylist check against the *actual* captured window happens here;
1071
+ * the caller discards the pixels if it fails.
1072
+ */
1073
+ declare function decidePostCapture(policy: ObserverPolicy, target: ResolvedCaptureTarget): CaptureDecision;
1074
+ /** True if the user has set any `observer.*` key in user_config. */
1075
+ declare function isObserverPolicyConfigured(db: Database): Promise<boolean>;
1076
+ /** Hint surfaced when a UI session starts with no observer policy configured. */
1077
+ declare const OBSERVER_POLICY_UNSET_HINT: string;
1078
+
1079
+ /**
1080
+ * Bridge between the ObserverPolicy (Layer 2) and the native Rust observer
1081
+ * sidecar. The sidecar reads a kernel-written policy file at
1082
+ * `<observer-dir>/policy.json` instead of its own `ZAM_OBSERVER_PRIVACY_POLICY`
1083
+ * env var, so the headless `capture-ui` path and the live sidecar share one
1084
+ * source of truth. See docs/adr/0001-observer-permission-model.md (item 4).
1085
+ */
1086
+
1087
+ /** Filename, under the observer dir, that the Rust sidecar reads. */
1088
+ declare const SIDECAR_POLICY_FILE = "policy.json";
1089
+ /**
1090
+ * The Rust observer's `WindowPrivacyPolicy` wire shape (serde camelCase). These
1091
+ * are only the user-configurable lists; the sidecar enforces its own
1092
+ * authoritative built-in sensitive set on top, exactly like the TS side.
1093
+ */
1094
+ interface SidecarPrivacyPolicy {
1095
+ allowProcesses: string[];
1096
+ denyProcesses: string[];
1097
+ denyTitleMarkers: string[];
1098
+ }
1099
+ /**
1100
+ * Pure mapping from an ObserverPolicy to the sidecar's `WindowPrivacyPolicy`.
1101
+ * A denylist term should block on process OR title, so it feeds both the
1102
+ * process and title-marker lists.
1103
+ */
1104
+ declare function toSidecarPrivacyPolicy(policy: ObserverPolicy): SidecarPrivacyPolicy;
1105
+ /**
1106
+ * Resolve the policy from settings and write the sidecar file. Returns the
1107
+ * path written and the serialized policy. The directory mirrors
1108
+ * `getUiObserverDir()`, which the Rust observer resolves identically
1109
+ * (`ZAM_OBSERVER_DIR`, else `~/.zam/observer`).
1110
+ */
1111
+ declare function syncObserverSidecarPolicy(db: Database, dir?: string): Promise<{
1112
+ path: string;
1113
+ policy: SidecarPrivacyPolicy;
1114
+ }>;
1115
+
970
1116
  /**
971
1117
  * Cascade Block & Unblock — prerequisite-aware blocking logic.
972
1118
  *
@@ -1730,4 +1876,4 @@ declare function resolveAllBeliefPaths(db: Database): Promise<string[]>;
1730
1876
  */
1731
1877
  declare function resolveAllGoalPaths(db: Database): Promise<string[]>;
1732
1878
 
1733
- export { type ADOConfig, type ADOCredentials, type AgentSkill, type AnalysisResult, type ApplySessionSynthesisInput, type ApplySessionSynthesisResult, type BloomLevel$1 as BloomLevel, type Card, type CardDeletionImpact, type CardState$1 as CardState, type CascadeBlockResult, type CommandRecord, type CommandSequence, type ConnectionOptions, type CreateAgentSkillInput, type CreateGoalInput, type CreateReviewInput, type CreateSessionInput, type CreateTokenInput, type Credentials, DEFAULT_REVIEW_CONTEXT_MAX_CHARS, type Database, type DatabaseProvider, type DatabaseValue, type DeleteCardResult, type DeleteTokenResult, type DiscoveryOptions, type DomainCompetence, type EvaluateInput, type EvaluateResult, type ExecuteReviewActionInput, type ExecutionContext, type FSRSParameters, type Goal, type GoalFrontmatter, type GoalStatus, type GoalSummary, HOMEBREW_CASK, type ImportResult, type InstallChannel, type InstallConfig, type InstallMode, type InstallPlan, type InstallResult, type LocalLLMRunner, type LogStepInput, type MonitorEvent, type Neighborhood, type NeighborhoodToken, type ObservationRating, type PrepareSessionSynthesisInput, type Prerequisite, type PrerequisiteWithToken, type PromptInput, type Rating, type RecallPrompt, type RemoteDatabaseOptions, type RepoPaths, type ResolvedReference, type ReviewActionResult, type ReviewActionType, type ReviewContext, type ReviewLog, type ReviewQueue, type ReviewQueueItem, type ReviewQueueOptions, type RunResult, SNAPSHOT_VERSION, type SchedulingCard, type Session, type SessionStep, type SessionSummary, type SessionSynthesisCandidate, type SessionSynthesisEvidence, type SessionSynthesisPreview, type SessionSynthesisRecord, type SkillProposal, type SkillSource, type SnapshotManifest, type Statement, type SupportedLocale, type SymbiosisMode, type SynthesisConfidence, type SystemProfile, type Token, type TokenDeleteImpact, type TokenPattern, type TranslationKey, type TursoCredentials, UI_OBSERVATION_PROTOCOL_VERSION, type UiActionType, type UiApplicationContext, type UiCandidateToken, type UiEvidenceRef, type UiEvidenceType, type UiObservationKind, type UiObservationReport, type UiObservedAction, type UnblockResult, type UpdateActionKind, type UpdateCardInput, type UpdateDecision, type UpdateTokenInput, type UserSetting, type UserStats, WINGET_PACKAGE_ID, type WorkItem, addPrerequisite, analyzeObservation, appendUiObservationReport, applySessionSynthesis, buildReviewQueue, buildUiSynthesisCandidates, cascadeBlock, clearADOCredentials, clearTursoCredentials, compareVersions, createAgentSkill, createFSRS, createGoal, createToken, decideUpdate, deleteCardForUser, deleteSetting, deleteToken, deprecateToken, detectSyncProvider, detectSystemLocale, discoverSkills, distributeGlobalSkills, endSession, ensureCard, ensureMonitorDir, ensureUiObserverDir, evaluateRating, executeReviewAction, exportSnapshot, extractTasks, extractTokenRefs, fetchActiveWorkItems, findTokens, generateBashHooks, generateBashUnhooks, generateConceptFreeCue, generatePowerShellHooks, generatePowerShellUnhooks, generatePrompt, generateZshHooks, generateZshUnhooks, getADOCredentials, getAgentSkill, getAllSettings, getAllSettingsDetailed, getBlockedCards, getCard, getCardById, getCardDeletionImpact, getDefaultDbPath, getDependents, getDomainCompetence, getDueCards, getGoal, getGoalTree, getInstallChannel, getInstallMode, getMonitorDir, getMonitorLogStats, getMonitorPath, getPackageSkillPath, getPrerequisites, getRepoPaths, getReviewsForCard, getReviewsForUser, getSessionSummary, getSessionSynthesisRecords, getSetting, getSystemProfile, getTokenById, getTokenBySlug, getTokenDeleteImpact, getTokenNeighborhood, getTursoCredentials, getUiObservationPath, getUiObserverDir, getUserStats, hasCommand, importSnapshot, injectShellHooks, installFastFlowLM, installOllama, installOpenCode, interleave, isUiObservationReport, listAgentSkills, listGoals, listTokens, loadADOConfig, loadCredentials, loadInstallConfig, logReview, logStep, matchesFilePath, monitorLogExists, normalizeLocale, normalizePath, openDatabase, openDatabaseWithSync, openRemoteDatabase, pairCommands, parseGoalFile, parseMonitorLog, parseSnapshot, parseUiObservationLog, planOpenCodeInstall, prepareLocalModel, prepareSessionSynthesis, readMonitorLog, readUiObservationLog, resolveAllBeliefPaths, resolveAllGoalPaths, resolveReference, resolveRepoPath, resolveReviewContext, saveCredentials, saveInstallConfig, serializeGoal, setADOCredentials, setInstallChannel, setInstallMode, setSetting, setTursoCredentials, startSession, t, uiObservationLogExists, uiObservationTimeSpan, unblockReady, updateCard, updateGoalStatus, updateToken, verifySnapshot, wouldCreateCycle, writeMonitorEvent };
1879
+ export { type ADOConfig, type ADOCredentials, type AgentSkill, type AnalysisResult, type ApplySessionSynthesisInput, type ApplySessionSynthesisResult, BUILT_IN_SENSITIVE_MATCHERS, type BloomLevel$1 as BloomLevel, type CaptureDecision, type CaptureDenialReason, type CaptureRequest, type Card, type CardDeletionImpact, type CardState$1 as CardState, type CascadeBlockResult, type CommandRecord, type CommandSequence, type ConnectionOptions, type CreateAgentSkillInput, type CreateGoalInput, type CreateReviewInput, type CreateSessionInput, type CreateTokenInput, type Credentials, DEFAULT_OBSERVER_POLICY, DEFAULT_REVIEW_CONTEXT_MAX_CHARS, type Database, type DatabaseProvider, type DatabaseTargetInfo, type DatabaseValue, type DeleteCardResult, type DeleteTokenResult, type DiscoveryOptions, type DomainCompetence, type EvaluateInput, type EvaluateResult, type ExecuteReviewActionInput, type ExecutionContext, type FSRSParameters, type Goal, type GoalFrontmatter, type GoalStatus, type GoalSummary, HOMEBREW_CASK, type ImportResult, type InstallChannel, type InstallConfig, type InstallMode, type InstallPlan, type InstallResult, type LocalLLMRunner, type LogStepInput, type MonitorEvent, type Neighborhood, type NeighborhoodToken, OBSERVER_POLICY_UNSET_HINT, OBSERVER_POLICY_VERSION, type ObservationRating, type ObserverConsent, type ObserverPolicy, type ObserverRetention, type ObserverScope, type ObserverSettingKey, type PrepareSessionSynthesisInput, type Prerequisite, type PrerequisiteWithToken, type PromptInput, type Rating, type RecallPrompt, type RemoteDatabaseOptions, type RepoPaths, type ResolvedCaptureTarget, type ResolvedReference, type ReviewActionResult, type ReviewActionType, type ReviewContext, type ReviewLog, type ReviewQueue, type ReviewQueueItem, type ReviewQueueOptions, type RunResult, SIDECAR_POLICY_FILE, SNAPSHOT_VERSION, type SchedulingCard, type Session, type SessionStep, type SessionSummary, type SessionSynthesisCandidate, type SessionSynthesisEvidence, type SessionSynthesisPreview, type SessionSynthesisRecord, type SidecarPrivacyPolicy, type SkillProposal, type SkillSource, type SnapshotManifest, type Statement, type SupportedLocale, type SymbiosisMode, type SynthesisConfidence, type SystemProfile, type Token, type TokenDeleteImpact, type TokenPattern, type TranslationKey, type TursoCredentials, UI_OBSERVATION_PROTOCOL_VERSION, type UiActionType, type UiApplicationContext, type UiCandidateToken, type UiEvidenceRef, type UiEvidenceType, type UiObservationKind, type UiObservationReport, type UiObservedAction, type UnblockResult, type UpdateActionKind, type UpdateCardInput, type UpdateDecision, type UpdateTokenInput, type UserSetting, type UserStats, WINGET_PACKAGE_ID, type WorkItem, addPrerequisite, analyzeObservation, appendUiObservationReport, applySessionSynthesis, buildReviewQueue, buildUiSynthesisCandidates, cascadeBlock, clearADOCredentials, clearTursoCredentials, compareVersions, createAgentSkill, createFSRS, createGoal, createToken, decidePostCapture, decidePreCapture, decideUpdate, deleteCardForUser, deleteSetting, deleteToken, deprecateToken, detectSyncProvider, detectSystemLocale, discoverSkills, distributeGlobalSkills, endSession, ensureCard, ensureMonitorDir, ensureUiObserverDir, evaluateRating, executeReviewAction, exportSnapshot, extractTasks, extractTokenRefs, fetchActiveWorkItems, findTokens, generateBashHooks, generateBashUnhooks, generateConceptFreeCue, generatePowerShellHooks, generatePowerShellUnhooks, generatePrompt, generateZshHooks, generateZshUnhooks, getADOCredentials, getAgentSkill, getAllSettings, getAllSettingsDetailed, getBlockedCards, getCard, getCardById, getCardDeletionImpact, getDatabaseTargetInfo, getDefaultDbPath, getDependents, getDomainCompetence, getDueCards, getGoal, getGoalTree, getInstallChannel, getInstallMode, getMonitorDir, getMonitorLogStats, getMonitorPath, getPackageSkillPath, getPrerequisites, getRepoPaths, getReviewsForCard, getReviewsForUser, getSessionSummary, getSessionSynthesisRecords, getSetting, getSystemProfile, getTokenById, getTokenBySlug, getTokenDeleteImpact, getTokenNeighborhood, getTursoCredentials, getUiObservationPath, getUiObserverDir, getUserStats, hasCommand, importSnapshot, injectShellHooks, installFastFlowLM, installOllama, installOpenCode, interleave, isObserverPolicyConfigured, isUiObservationReport, listAgentSkills, listGoals, listTokens, loadADOConfig, loadCredentials, loadInstallConfig, logReview, logStep, matchBuiltInSensitive, matchDenylist, matchesFilePath, monitorLogExists, normalizeLocale, normalizePath, openDatabase, openDatabaseWithSync, openRemoteDatabase, pairCommands, parseGoalFile, parseMonitorLog, parseObserverList, parseObserverPolicy, parseSnapshot, parseUiObservationLog, planOpenCodeInstall, prepareLocalModel, prepareSessionSynthesis, readMonitorLog, readUiObservationLog, resolveAllBeliefPaths, resolveAllGoalPaths, resolveObserverPolicy, resolveReference, resolveRepoPath, resolveReviewContext, saveCredentials, saveInstallConfig, serializeGoal, setADOCredentials, setInstallChannel, setInstallMode, setSetting, setTursoCredentials, startSession, syncObserverSidecarPolicy, t, toSidecarPrivacyPolicy, uiObservationLogExists, uiObservationTimeSpan, unblockReady, updateCard, updateGoalStatus, updateToken, verifySnapshot, wouldCreateCycle, writeMonitorEvent };